Home > Software engineering >  Trying to malloc a typedef 2d array
Trying to malloc a typedef 2d array

Time:01-13

I've declared a typedef:

typedef float Matrix[3][3];

And I'm now trying to allocate memory for that array:

Matrix* matPtr = malloc(sizeof(Matrix));

if (matPtr != NULL)
{
    for (int r = 0; r < 3; r  )
    {
        for (int c = 0; c < 3; c  )
        {
            *matPtr[r][c] = 0; 
        }
    }
}

But I'm getting the error:

Severity Code Description Project File Line Suppression State Warning C6200 Index '2' is out of valid index range '0' to '0' for non-stack buffer 'matPtr'.

What am I doing wrong?

CodePudding user response:

  1. Do not hide arrays and pointers behind typedefs. It is a very very bad practice.
  2. Use pointers to array
int (*matrix)[3] = malloc(3 * sizeof(*matrix));

and use as a normal matrix

matrix[1][2] = 5;
  •  Tags:  
  • Related