gpt4 book ai didi

c - 如何在 C 中动态分配二维数组?

转载 作者:行者123 更新时间:2023-11-30 18:12:52 24 4
gpt4 key购买 nike

所以我有一个带有结构的程序

typedef struct s_struct {
int rows;
int cols;
char* two_d; //This is supposed to be the 2D array
} *GRID;

我想创建一个 Strike 并为其动态分配内存,然后填充 2D 数组,但我不知道如何操作。这是我对 create(int prows, int pcols) 函数的了解:

GRID grid = malloc(sizeof(struct s_struct));
grid ->rows = prows;
grid ->cols = pcols;
grid ->two_d = malloc(sizeof(char) * (rows*cols));

我不明白这是如何创建一个二维数组(如果确实如此)以及如何填充该数组。

最佳答案

这一行:

grid ->two_d = malloc(sizeof(char) * (rows*cols));

分配一个“内存中连续”的网格/矩阵可以引用:

grid[row_offset][cols_offset]

其中“row_offset”可以是 0...(row-1)

其中“cols_offset”可以是 0...(cols-1)

note: 'sizeof(char)' is always 1, 
so including that phrase
in the malloc parameter just clutters the code
because '(1*something)' is always 'something'
as the 1 has no effect.

建议:从 malloc 参数中删除“sizeof(char)”

关于c - 如何在 C 中动态分配二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29689611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com