c - 将二维数组分配给结构体对象

标签 c arrays pointers multidimensional-array malloc

我有二维数组。我希望将该数组分配给结构。请看一下:

这是我的结构:

typedef struct {
    int x;
    int y;
    char **table; //2-dim array
} some_struct;

我希望能够分配这个:

const char sth1_table[2][3] = {
   { ' ', 'x', ' '},
   { 'x', 'x', 'x'},
};

或者这个:

const char sth2_table[4][2] = {
   { 'x', ' '},
   { 'x', ' '},
   { 'x', ' '},
   { 'x', 'x'},
};

到该结构。

如何做到这一点? 我尝试分配:

new_sth.table = malloc(sizeof(sth1_table));
*new_sth.table = sth1_table;

然后访问:

some_struct get_sth;
get_sth = *(some_struct+i);
other_array[a][b] = get_sth.table[a][b];

但运气不佳。

我做错了什么?

最佳答案

对于初学者来说,成员table不是二维数组。它是一个指针。

数组没有赋值运算符。您必须逐个元素复制数组。

例如,如果您有一个结构对象

typedef struct {
    int x;
    int y;
    char **table; // pointer
} some_struct;

some_struct obj;

和数组

const char sth1_table[2][3] = {
   { ' ', 'x', ' '},
   { 'x', 'x', 'x'},
};

那么你可以采用以下方式

obj.table = malloc( sizeof( char *[2] ) );

for ( size_t i = 0; i < 2; i++ )
{
    obj.table[i] = malloc( sizeof( sth1_table[i] ) );
    memcpy( obj.table[i], sth1_table[i], sizeof( sth1_table[i] ) );
} 

您应该记住,当您需要使用另一个二维数组作为初始值设定项时,必须释放所有分配的内存或重新分配它。

关于c - 将二维数组分配给结构体对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35040926/

相关文章:

python - Python 内部是如何存储日期时间的?

C 代码卡在 scanf() 语句

python - 将一条线拟合到python中的矩阵

python - NumPy 的 transpose() 方法如何置换数组的轴?

c - 解释这段代码的正确方法是什么?

c - 从用户那里获取字符串的更好方法

c++ - 为什么我在 clrscr(); 中遇到错误它说未定义?

c - 使用链表实现简单队列

arrays - 在 perl 中为数组预分配内存有什么用?

C 段错误(核心转储)