重新分配一个结构体,c

发布于 2024-11-29 17:21:54 字数 212 浏览 0 评论 0原文

我有下一个结构

struct Board
{
    int width;
    int height;
    char **board;
}

,我想扩展 **board,这意味着我需要更多内存,因此需要调用 重新分配()。所以我的问题是我该怎么做 - 我应该在数组中的每一行分别调用 realloc() 并在整个结构上调用它吗? 谢谢!

I have the next struct

struct Board
{
    int width;
    int height;
    char **board;
}

And I would like to expand the **board, meaning I need more memory and thus the call to
realloc(). So my question is how do I do that - should I call realloc() on every line in the array separatly and the call it on the entire struct?
Thanks!

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

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

发布评论

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

评论(4

自我难过 2024-12-06 17:21:54

board调用realloc将元素数量加1,然后对board[height]调用malloc (假设高度是第一个维度)添加新行

Call realloc for board to increase the number of elements by 1, and then call malloc on board[height] (assuming height is the first dimension) to add a new row

您的好友蓝忘机已上羡 2024-12-06 17:21:54

您需要在 board 上调用 malloc 而不是 realloc。当实例化 Board 对象时,不会为成员 board 分配内存;所以这不是重新分配内存的问题,而是以多维数组

#include <stdlib.h>

int **array;
array = malloc(nrows * sizeof(int *));
if(array == NULL)
    {
    fprintf(stderr, "out of memory\n");
    exit or return
    }
for(i = 0; i < nrows; i++)
    {
    array[i] = malloc(ncolumns * sizeof(int));
    if(array[i] == NULL)
        {
        fprintf(stderr, "out of memory\n");
        exit or return
        }
    }

一旦您分配了内存,然后如果您需要扩展board(例如board最初是2x2,现在您希望它是6x6),请调用realloc 的顺序与调用 malloc 初始化 board 的顺序相同。

You need to call malloc not realloc on board. When you instantiate an object of Board, no memory is allocated to the member board ; so it's not a question of reallocating memory, but allocating memory to board in the usual way for multidimensional arrays.

#include <stdlib.h>

int **array;
array = malloc(nrows * sizeof(int *));
if(array == NULL)
    {
    fprintf(stderr, "out of memory\n");
    exit or return
    }
for(i = 0; i < nrows; i++)
    {
    array[i] = malloc(ncolumns * sizeof(int));
    if(array[i] == NULL)
        {
        fprintf(stderr, "out of memory\n");
        exit or return
        }
    }

Once, you've allocated memory, and then if you need to expand board (e.g. board was initially 2x2 and now you want it to be 6x6), call realloc in the same order you called malloc to initialize board.

治碍 2024-12-06 17:21:54

如果你想要更多的行,你应该在board上调用realloc,如果你想扩展行,你需要在你的每一行上调用realloc先前分配的(例如 board[0]board[1] 等)

If you want more lines, you should call realloc on board, if you want to expand lines, you need to call realloc on each line you previously allocated (e.g. board[0], board[1] etc)

温柔一刀 2024-12-06 17:21:54

如果您可以预测需要多少内存,那么最好只调用一次。否则可能会大大减慢整个过程。

If you can predict how much memory you need, it would be the best to only call it once. Doing otherwise might slow down the whole suff massively.

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