[英]Assigning 2-dimensional array to struct object
我有二维数组。 我希望将该数组分配给struct。 请看一下:
这是我的结构:
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] ) );
}
您应该记住,当您需要使用另一个二维数组作为初始化程序时,必须释放所有分配的内存或重新分配它。
如果您可以使用硬编码的数组大小而不使用malloc做到这一点,那么我将考虑以下示例:
#include <stdio.h>
#include <stdlib.h>
struct Some_Struct
{
int x;
int y;
char sth1_table[2][3];
char sth2_table[4][4];
};
int main ( int argc, char *argv[] )
{
struct Some_Struct yy;
struct Some_Struct zz[10];
yy.x = 1;
yy.y = 2;
/*
you wanted this
const char sth1_table[2][3] = {
{ ' ', 'a', ' '},
{ 'b', 'c', 'd'},
};
*/
yy.sth1_table[0][0] = '\0'; /* null character */
yy.sth1_table[0][1] = 'a';
yy.sth1_table[0][2] = '\0';
yy.sth1_table[1][0] = 'b';
yy.sth1_table[1][1] = 'c';
yy.sth1_table[1][2] = 'd';
for ( i = 0; i < 10; i++ )
{
zz[i].sth1_table[0][0] = '\0'; /* null character */
zz[i].sth1_table[0][1] = 'a';
zz[i].sth1_table[0][2] = '\0';
zz[i].sth1_table[1][0] = 'b';
zz[i].sth1_table[1][1] = 'c';
zz[i].sth1_table[1][2] = 'd';
}
}
如果您对运行时分配感兴趣,那么除了malloc()之外,还要考虑calloc()函数。 这样做时,请记住2维数组(或3维,4维,任意维)的内存分配只是一块内存,其大小是维数乘以类型大小。
char sth1_table[2][3];
char的大小为1个字节。 1个字节* 2 * 3 = sth1_table的6个字节的内存
char sth2_table[4][4];
1个字节* 4 * 4 = 16个字节的存储器sth2_table
然后,如何选择在已分配内存中排序数据的方式(无论是行第一还是列第一)完全取决于您。
建议不要为内存分配定义一个宏,而不是直接使用malloc 。 这使代码更易于遵循。 在下面的示例中,我可以随意重命名一些标识符。
#include <stdio.h>
#include <stdlib.h>
#define LEN(arr) (sizeof (arr) / sizeof (arr)[0])
#define NEW_ARRAY(ptr, n) (ptr) = malloc((n) * sizeof (ptr)[0])
typedef struct {
int m;
int n;
char **table;
} Matrix;
int main()
{
const char items[2][3] = {{' ', 'x', ' '}, {'x', 'x', 'x'}};
Matrix A;
int i, j;
A.m = LEN(items);
A.n = LEN(items[0]);
/*initialize matrix*/
NEW_ARRAY(A.table, A.m);
for (i = 0; i < A.m; i++) {
NEW_ARRAY(A.table[i], A.n);
for (j = 0; j < A.n; j++) {
A.table[i][j] = items[i][j];
}
}
/*print matrix*/
for (i = 0; i < A.m; i++) {
for (j = 0; j < A.n; j++) {
printf("%c ", A.table[i][j]);
}
putchar('\n');
}
return 0 ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.