Search code examples
carrayspointers2ddynamic-allocation

Dynamic 2D array - allocation won't work (segfault)


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);
}

Solution

  • 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.