在运行时设置数组大小
我知道如何在函数内创建结构数组:
typedef struct item { int test; }; void func (void) { int arraysize = 5; item ar[arraysize]; }
但是,当全局声明数组时,我该怎么做?
typedef struct item { int test; }; item ar[]; void func (void) { int arraysize = 5; // What to here? }
可能你喜欢这个:
typedef struct item { int test; }; item *arr; void func (void) { int arraysize = 5; arr = calloc(arraysize,sizeof(item)); // check if arr!=NULL : allocation fail! // do your work free(arr); }
但它的动态配置!
如果在编译时知道arraysize
。 然后更好地创建这样的宏:
#define arraysize 5 typedef struct item { int test; }; item arr[arraysize];
使用大写的宏观常量的旁注是很好的做法
对于具有自动存储持续时间的arrays,仅允许C中的可变长度数组。 在文件范围声明的数组具有静态存储持续时间,因此不能是可变长度数组。
您可以使用malloc
为编译时大小未知的数组对象动态分配内存。
item * ar: int count; void foo() { count = 5; ar = malloc(sizeof(item) * count); // check to make sure it is not null... }
typedef struct item { int test; }; #define ARRAYSIZE 5 item ar[ARRAYSIZE];
您无法在运行时修改数组的大小。 您可以执行动态内存分配并在需要时调用realloc()
。
编辑:在你的情况下,我建议像这样做一些事情:
item *ar; void func(void) { int arraysize = 5; ar = malloc(arsize); if(ar) { /* do something */ } //don't forget to free(ar) when no longer needed }