malloc参数太多。

我分配了一个二维数组。 2d数组是结构的一部分,当我尝试使用malloc时,我收到一个错误,指出malloc的参数过多。
malloc(world->representation, sizeof(int *) * mapHeight);
int i;
for (i = 0; i < mapHeight, i++ )
{
    malloc(world->representation[i], sizeof(int) * mapWidth);
}
如果它是结构的一部分,应该如何分配呢?     
已邀请:
您没有正确使用ѭ1。正确的用法是:
world->representation = malloc(sizeof(int *) * mapHeight);
world->representation[i] = malloc(sizeof(int) * mapWidth);
    
malloc只取大小,然后返回指向已分配内存的指针。     
应该:
world->representation[i] = malloc( sizeof(int) * mapWidth);
    
malloc返回其内存,但不填充它。您还应该检查返回值以确保其为非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()只有1个参数,它是您要分配的块的大小,然后必须将其类型转换为相应的指针类型 您的代码很可能是:
world->representation = (int **) malloc(sizeof(int *) * mapHeight);
int i;
for (i = 0; i < mapHeight, i++ ) {
    *(world->representation+i) = (int *) malloc(sizeof(int) * mapWidth);
}
    

要回复问题请先登录注册