[英]Declaring and Initializing 2D array of unknown size in C
我计划创建一个从typedef struct
派生的指针的2D数组
假设typedef struct
名为“Items”,并包含字符串和整数的混合变量。
我将声明两个int
变量,即typenum
和typetotal
。 这两个整数将从零开始,并在输入数据与某个函数匹配时相加。
在数组中, Items *type[][]
,基本上type[][]
是Items *type[typenum][typetotal]
但我不能这样做,因为我会在声明部分声明typenum
和typetotal
为零。
我尝试通过Items *type[][] = {{0},{0}}
初始化数组Items *type[][] = {{0},{0}}
但这会产生错误。
有什么建议? 有人告诉我在这上面使用malloc(),但我根本就不知道怎么做。
*在Windows上使用Tiny C.
使用动态内存分配。
Items **type;
type = malloc(sizeof (Items *) * typenum);
for (int i = 0; i < typenum; i++)
type[i] = malloc(sizeof Items) * typetotal);
使用阵列后,您需要手动释放分配的内存。
for (int i = 0; i < typenum; i++)
free(types[i]);
free(types);
这是一个关于它的教程: http : //www.eskimo.com/~scs/cclass/int/sx9b.html
如果在程序运行时typenum
和typetotal
增加,请确保使用realloc
,这将重新分配更多内存并保留内容。 您需要像这样分配数组的第一个维度:
myArray = realloc(myArray, sizeof(Items*) * typenum);
然后为第一个维度分配第二个维度:
for(...)
myArray[i] = realloc(myArray[i], sizeof(Items) * typetotal);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.