I malloc a 2d array. The 2d array is part of a struct and when I 开发者_Python百科try malloc is I get an error that malloc has too many arguments.
malloc(world->representation, sizeof(int *) * mapHeight);
int i;
for (i = 0; i < mapHeight, i++ )
{
malloc(world->representation[i], sizeof(int) * mapWidth);
}
How should this be malloced if its part of a struct?
You are using malloc
incorrectly. The proper usage is:
world->representation = malloc(sizeof(int *) * mapHeight);
and
world->representation[i] = malloc(sizeof(int) * mapWidth);
malloc takes just the size and returns pointer to the allocated memory.
Should be:
world->representation[i] = malloc( sizeof(int) * mapWidth);
malloc returns its memory, it doesn't fill it in. You should also check the return value to make sure it is non-NULL:
world->representation = malloc(sizeof(world->representation[0]) * mapHeight);
assert(world->representation);
int i;
for (i = 0; i < mapHeight; ++i) {
world->representation[i] = malloc(sizeof(word->representation[i][0]) * mapWidth);
assert(world->representation[i]);
}
malloc() has only 1 argument which is the size of the chunk you want allocated, then you'd have to type cast it to the respective pointer type
Most probably your code would be:
world->representation = (int **) malloc(sizeof(int *) * mapHeight);
int i;
for (i = 0; i < mapHeight, i++ ) {
*(world->representation+i) = (int *) malloc(sizeof(int) * mapWidth);
}
精彩评论