【问题标题】:How can I have a dynamically allocated 2D array in C? [duplicate]如何在 C 中动态分配二维数组? [复制]
【发布时间】:2015-06-23 17:43:44
【问题描述】:

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

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

我想创建一个打击并动态为其分配内存,然后填充二维数组,但我不知道如何。这是我对 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));

我不明白它是如何创建一个二维数组的,以及如何填充数组。

【问题讨论】:

  • This 可能会有所帮助。
  • @Axalo 非常感谢。我会读一读
  • 有很多关于这个主题的帖子。结帐stackoverflow.com/search?q=[c]+create+dynamic+2D+array
  • fdo 不 typedef 结构定义。它使代码混乱,导致误解,并使编译器名称空间混乱。那么标签名称“s_struct”没有提供信息。更好的是'grid_t。然后在所有未来的参考中使用'struct grid_t'。注意:所有大写的“GRID”(按照编程约定)为宏/#define 名称保留。

标签: c arrays pointers struct dynamic-memory-allocation


【解决方案1】:

这一行:

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)'

【讨论】:

  • grid[row_offset][cols_offset]无法访问
猜你喜欢
  • 2013-11-14
  • 2021-02-03
  • 2017-09-28
  • 1970-01-01
  • 2015-09-17
  • 1970-01-01
  • 1970-01-01
  • 2021-01-26
相关资源
最近更新 更多