C++ program return an array

OP #6303886
Hey guys
I am new with c++ and I have to write a code, but somehow it is not 
working and I do not know what I can change. I would like to give back 
the array Grad, but it says segmentation fault (core dumped).
Could somebody help me what I have to change?
Or is it possible to have a global variable and write from the function 
directly to the global variable?
Thanks for your help.

Code:
double* Gradient(const double x[], int n1) {
    double Grad [n1*4] = {0};
    // We calculate the overlap. If the overlap is zero, the gradient
    // is also zero. This should be probably improved in the future.
    //int n = sizeof(x)/32;
    for (int i = 0; i < n1*4; i++)
    {
        for (int j = 0; j < n1*4; i++)
        {
            if (i != j)
            {
                //cout << x[i]<< endl;
                double xmin = max(x[i*4], x[j*4]);
                double xmax = min(x[i*4+1], x[j*4+1]);
                //if (xmin > xmax) return Grad;
                double ymin = max(x[i*4+2], x[j*4+2]);
                double ymax = min(x[i*4+3], x[j*4+3]);
                //if (ymin > ymax) return Grad;

                double x_overlap = xmax-xmin;
                double y_overlap = ymax-ymin;

                // Gradient for xmin
                if (x[i*4] >= x[j*4] && x[i*4] != x[j*4+1] && x[i*4+1] 
!= x[j*4] && x[i*4+2] != x[j*4+3] && x[i*4+3] != x[j*4+2]) Grad[i*4] = 
Grad[i*4]-y_overlap;

                // Gradient for xmax
                if (x[i*4+1] < x[j*4+1]) Grad[i*4+1] = Grad[i*4+1] + 
y_overlap;

                // Gradient for ymin
                if (x[i*4+2] >= x[j*4+2] && x[i*4] != x[j*4+1] && 
x[i*4+1] != x[j*4] && x[i*4+2] != x[j*4+3] && x[i*4+3] != x[j*4+2]) 
Grad[i*4+2] = Grad[i*4+2]-x_overlap;

                // Gradient for ymax
                if (x[i*4+3] <= x[j*4+3]) Grad[i*4+3] = Grad[i*4+3] + 
x_overlap;

                // Gradient for xmax if rectangles are touching by the 
x-coordinate
                if (x[i*4+1] == x[j*4] && x[i*4+3] > x[j*4+2] && 
x[i*4+2] < x[j*4+3])
                {
                    Grad[i*4+1] = Grad[i*4+1] + y_overlap;
                }

                // Gradient for ymax if rectangles are touching by the 
y-coordinate
                if (x[i*4+3] == x[j*4+2] && x[i*4+1] > x[j*4] && x[i*4] 
< x[j*4+1])
                {
                    Grad[i*4+3] = Grad[i*4+3] + x_overlap;
                }
            }
        }
    }
    return Grad;
}


int main() {
    // Coordinates of the rectangles
    double x[] = {0,6,0,9,3,9,4,11};
    int n1 = sizeof(x)/32;

    double gradient;
    gradient = Gradient(x,n1);

    cout << "Gradient R1 xmin = " << Gradient[0] << endl;
}
Gast #6303900
Hi,

I haven't read through all of your code yet but there are two 
conceptional problems within the first two lines already. ;)

Code:
double* Gradient(const double x[], int n1) {
    double Grad [n1*4] = {0};


1) You cannot define an array using a variable for its size. It has to 
be constant.

These two ways are allowed:
double grad[5]; // or use a named constant, e.g. MY_ARRAY_SIZE
double grad[] = {1,2,3,4,5};

while this one is not:
int size=5;
double grad[size];


2) You're defining the array (double Grad[]) inside the gradient() 
function and let it return a pointer to that array. Unfortunately, 
Grad[] doesn't exists anymore, once the function gradient() has exited. 
This is probably, what causes the segfault.


If you really HAVE TO use a variable array size (Which doesn't make much 
sense on a µC btw.) then you should have a look at 'new' and 'delete' 
which corresponds to malloc/free in C.

Also, you have to define your grad-Array outside the gradient() 
function. And instead having gradient() return a pointer, you would just 
pass a reference to the grad-Array as parameter when calling gradient.
This procedure is called: CallByReference.
gradient() would then initialize the grad-Array and write to it.

hth
#6303907
Moritz O. schrieb:
> Hey guys
> I am new with c++ and I have to write a code, but somehow it is not
> working and I do not know what I can change. I would like to give back
> the array Grad, but it says segmentation fault (core dumped).

You should crank up the warning settings of your compiler. There are 
multiple issues that the compiler should have warned about. There should 
also be multiple errors, so I don't know how you got your compiler to 
accept that code.

> Could somebody help me what I have to change?

The problem is that you return a pointer to a local array. The variable 
Grad exists only as long as the function Gradient is running. But you 
return a pointer to it, so in main(), you are accessing a pointer to a 
non-existant object.

> Or is it possible to have a global variable and write from the function
> directly to the global variable?

It is possible, but not a good idea.
#6303928
Moritz O. schrieb:
> Or is it possible to have a global variable and write from the function
> directly to the global variable?

There is a way in the middle.

Define the array in the caller function (in your example: in main) and 
give the address of this array to your function.

(strcpy, fgets and other standard functions do this also)

Antwort schreiben

Eine eigene Frage? Dieser Thread ist über 6 Jahre alt. Stell sie in einem eigenen Thread – dort lesen mehr Leute mit, und sie wird öfter und schneller beantwortet.

Neuen Thread starten

Eine Lösung, Ergänzung oder Rückmeldung zu diesem Thread? Dann antworte hier.

Formatierung
  • [c]C-Code[/c]
  • [code]Code in anderen Sprachen, ASCII-Zeichnungen[/code]
  • [math]Formel in LaTeX-Syntax[/math]
  • [[Titel]] – Link zu einem Artikel
  • Verweis auf einen anderen Beitrag: Rechtsklick auf dessen Beitrags-ID (#8078628), „Adresse kopieren“, in den Text einfügen

Mehr zur Formatierung

Längeren Sourcecode als Anhang, nicht in den Text. JPG nur für Fotos und Scans; Zeichnungen und Screenshots als PNG oder GIF. Siehe Bildformate.

Schon registriert? Anmelden

Wird nicht angezeigt. Wir schicken dir einen Link; sobald du damit bestätigst, erscheint dein Beitrag.

Mit dem Abschicken legst du einen kostenlosen Account an und erkennst die Nutzungsbedingungen und die Datenschutzerklärung an.