在运行时设置的数组大小 [英] Set array size at runtime
本文介绍了在运行时设置的数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道如何创建一个函数内部的结构数组:
typedef结构项目
{
INT测试;
};无效FUNC(无效)
{
INT ARRAYSIZE = 5;
AR [ARRAYSIZE]项目;
}
但我怎么到同一时阵列全局声明:
typedef结构项目
{
INT测试;
};AR []项目;无效FUNC(无效)
{
INT ARRAYSIZE = 5;
//怎么在这里?
}
解决方案
可能是你这样的:
typedef结构项目
{
INT测试;
};项目* ARR;无效FUNC(无效)
{
INT ARRAYSIZE = 5;
ARR =释放calloc(ARRAYSIZE,sizeof的(项目));
//检查是否ARR = NULL:分配失败!
// 做你的工作 免费(ARR);
}
但它的动态分配!
如果 ARRAYSIZE
的在编译时已知的。那么最好创建一个宏是这样的:
的#define ARRAYSIZE 5typedef结构项目
{
INT测试;
};ARR [ARRAYSIZE]项目;
<子>使用大写宏常量侧面说明是很好的做法
I know how to create a structure array inside a function:
typedef struct item
{
int test;
};
void func (void)
{
int arraysize = 5;
item ar[arraysize];
}
But how do I to the same when the array is declared globally:
typedef struct item
{
int test;
};
item ar[];
void func (void)
{
int arraysize = 5;
// What to here?
}
解决方案
May be you like this:
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);
}
But its dynamic allocation!
And if arraysize
known at compilation time. then better to create a macro like this:
#define arraysize 5
typedef struct item
{
int test;
};
item arr[arraysize];
side note using upper case for macro constants is good practice
这篇关于在运行时设置的数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文