Search code examples
cdynamic-memory-allocation

Dynamically allocating a float matrix?


Is there any way how to malloc() a 2D matrix in C? I have successfully tried malloc()ing a 1D field, but in matrix I am getting errors.


Solution

  • float *mat2d = malloc( rows * cols * sizeof( float ));

    to access a value from the matrix use this adressing scheme:

    float val = mat2d[ x + y * cols ];