0

Why wouldn't this work? I've reviewed my code several times and just can't find what's wrong.

Thanks!

void generateData(float** inData, int x, int y){
    inData[0][0]= 3000.0; // SEGFAULT
}

float** createMatrix(int x, int y){
    float** array= malloc(sizeof(float*) * y);
    for(int i=0; i<y; i++)
        array[i] = malloc(sizeof(float) * x);
}

int main(int argc, char** argv) {
    float** arr = createMatrix(100,2);

    generateData(arr, 100, 2);

    return(0);
}
c0dehunter
  • 6,412
  • 16
  • 77
  • 139

3 Answers3

3

You forgot this ever so important line;

return array;

in createMatrix. Look at your compiler warnings, or turn them on if you don't already have them on.

Dan F
  • 17,654
  • 5
  • 72
  • 110
0

Not sure if this snippet directly relates to your code, but you never returned the address from createMatrix().

dans3itz
  • 1,605
  • 14
  • 12
0

return array; is one problem in you code. Apart from that one more big problem is there.

float** array= malloc(sizeof(float*) * y); - You are first allocating memory for array to store array of pointers(to float). And then you are allocating memory for each row malloc(sizeof(float) * x);

Now you have allocated memory for 2 rows and 100 columns.Then Call generateData(arr, 100, 2);. In generateData if you do like inData[100][2] this will leads to crash. Because you have allocated only 2 rows and each rows has 100 elements. inData[100][2] is equivalent to *( *(inData + 100) + 2). Here *(inData + 100) will leads to crash(undefined behaviour). Because you are suppose to access only upto index 1 not 100.

Mistake is in createMatrix function, you have wrongly used the x and y. Rewrite your function like below.

float** createMatrix(int x, int y)
{
    int i;
    float** array= (float **)malloc(sizeof(float*) * x);
    for(int i=0; i<x; i++)
    {
        array[i] = (float *)malloc(sizeof(float) * y);
    }
    return array;
}

And also rewrite your generateData also as below.

void generateData(float** inData, int x, int y)
{
    x--;
    y--;    
    inData[i][j]= 3000.0; //Do you assignment to array here
}
rashok
  • 12,790
  • 16
  • 88
  • 100