malloc 有太多参数

发布于 2024-11-01 17:45:09 字数 300 浏览 0 评论 0原文

我 malloc 一个二维数组。二维数组是结构的一部分,当我尝试 malloc 时,我收到一个错误,指出 malloc 有太多参数。

malloc(world->representation, sizeof(int *) * mapHeight);
int i;
for (i = 0; i < mapHeight, i++ )
{
    malloc(world->representation[i], sizeof(int) * mapWidth);
}

如果它是结构的一部分,应该如何分配它?

I malloc a 2d array. The 2d array is part of a struct and when I 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

朦胧时间 2024-11-08 17:45:09

您错误地使用了malloc。正确的用法是:

world->representation = malloc(sizeof(int *) * mapHeight);

world->representation[i] = malloc(sizeof(int) * mapWidth);

You are using malloc incorrectly. The proper usage is:

world->representation = malloc(sizeof(int *) * mapHeight);

and

world->representation[i] = malloc(sizeof(int) * mapWidth);
千柳 2024-11-08 17:45:09

malloc 仅获取大小并返回指向已分配内存的指针。

malloc takes just the size and returns pointer to the allocated memory.

傾旎 2024-11-08 17:45:09

应该是:

world->representation[i] = malloc( sizeof(int) * mapWidth);

Should be:

world->representation[i] = malloc( sizeof(int) * mapWidth);
回梦 2024-11-08 17:45:09

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 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]);
}
小嗷兮 2024-11-08 17:45:09

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);
}

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文