我有二维数组。我希望将该数组分配给结构。请看一下:
这是我的结构:
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/