在C中初始化结构体中的数组
struct myStruct
{
short int myarr[1000];//want to initialize all elements to 0
}
如何初始化数组?
我尝试在结构内执行 short int* myarr[1000]={0}
但这是错误的。我该怎么做?我不介意在实现文件中这样做。该结构包含在头文件中。
struct myStruct
{
short int myarr[1000];//want to initialize all elements to 0
}
How do I initialize the array?
I tried doing short int* myarr[1000]={0}
inside the struct but it's wrong. How can I do this? I don't mind doing it in the implementation file. This struct is contained in a header file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用通用初始值设定项:
{0}
。通用初始化器适用于任何东西,并将元素初始化为正确的 0(对于指针,
NULL
,对于整数,0
,对于双精度数,0.0
,.. .):编辑动态分配的对象。
如果您要动态分配内存,请使用
calloc
而不是malloc
。对于 realloc(以及可能的其他情况),您需要
memset
。Use the universal initializer:
{0}
.The universal initializer works for anything and initializes the elements to the proper 0 (
NULL
for pointers,0
for ints,0.0
for doubles, ...):Edit for dynamically allocated objects.
If you're allocating memory dynamically use
calloc
rather thanmalloc
.With realloc (and possibly other situations) you need to
memset
.如果它是在函数之外(而不是在堆栈上)声明的,则整个结构将在编译时归零。
否则,您可以在声明后使用memset。
If it is declared out of a function (not on the stack), the whole struct will be zeroed at compile time.
Otherwise, you can use
memset
after declaring it.只需使用 {0} 初始化该结构的实例,这也会将您的数组归零。或者,按照 NKCSS 的演示使用 memset。
Just initialize an instance of the struct with {0}, this will zero your array as well. Alternatively, use memset as NKCSS demonstrates.
int 不是引用类型,它们在为结构分配内存后不会被初始化吗?
你可以这样做:
memset(&myStruct, 0, sizeof(myStruct));
int's arn't reference types, don't they get initialized after allocating memory for your structure?
You could just do this:
memset(&myStruct, 0, sizeof(myStruct));