如何在C中动态分配2D数组?
所以我有一个带结构的程序
typedef struct s_struct { int rows; int cols; char* two_d; //This is supposed to be the 2D array } *GRID;
我想创建一个敲击并动态分配内存,然后填充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));
我不明白这是如何创建一个2D数组,如果它甚至如此,以及如何填充数组。
这一行:
grid ->two_d = malloc(sizeof(char) * (rows*cols));
分配一个’连续内存’网格/矩阵,可以通过以下方式引用:
grid[row_offset][cols_offset]
‘row_offset’可以是0 …(第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)’