Pergunta

I couldn't find answer of the exact question, since the condition is a bit more specific: How can i allocate array of struct pointers.

typedef struct COORDS
{
  int xp;
  int yp;
} coord;

coord** xy;

i want to allocate it like: xy[500][460] But it returns invalid memory error when accessing them.

Foi útil?

Solução 2

Static allocation:

coord xy[500][460];

Dynamic allocation:

coord** xy = (coord**)malloc(sizeof(coord*)*500);
for (int i=0; i<500; i++)
    xy[i] = (coord*)malloc(sizeof(coord)*460);

// and at a later point in the execution of your program
for (int i=0; i<500; i++)
    free(xy[i]);
free(xy);

Outras dicas

coord** new = malloc (500 * sizeof (coord*));
int idx = 0;

for(; idx < 500; ++idx)
    new [idx] = malloc (460 * sizeof (coord));
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top