怎样才可以有一个在C动态分配的二维数组? [英] How can I have a dynamically allocated 2D array in C?

查看:158
本文介绍了怎样才可以有一个在C动态分配的二维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个程序与结构

So I have a program with a struct

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

我想创建一个击中,动态分配内存,然后填写二维数组,但我不知道怎么办。以下是我对创建(INT PROWS,诠释pcols)功能:

I want to create a struck and dynamically allocate memory to it and then fill the 2D array but I don't know how. Here is what I have for the create(int prows, int pcols) function:

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

我不明白这是如何创建如果它甚至做一个二维数组,我怎么能去填充数组。

I don't understand how this creates a 2D array if it even does and how I can go about filling the array.

推荐答案

这行:

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

分配一个内存连续网格/矩阵
可以由被引用

allocates a 'continuous in memory' grid/matrix that can be referenced by:

grid[row_offset][cols_offset]

,其中row_offset'可以是0 ...(行1)

where the 'row_offset' can be 0...(row-1)

,其中cols_offset'可以是0 ...(COLS-1)

where the 'cols_offset' can be 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)的

suggest: remove the 'sizeof(char)' from the malloc parameter

这篇关于怎样才可以有一个在C动态分配的二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆