开发者

realloc a struct, c

开发者 https://www.devze.com 2023-03-28 23:30 出处:网络
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

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 - shou开发者_运维百科ld I call realloc() on every line in the array separatly and the call it on the entire struct? Thanks!


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


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.


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)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号