[英]Array initialization
As per suggestions I have modified the code, but how can I initialize single element in the structure ?? 根据建议我修改了代码,但是如何在结构中初始化单个元素?
#include<stdio.h>
typedef struct student
{
int roll_id[10];
int name_id[10];
} student;
int main()
{
student p = { {0} }; // if i want to initialize single element ''FIX HERE, PLs''
student *pptr=&p;
pptr->roll_id[9]={0}; // here is the error pointed
printf (" %d\n", pptr->roll_id[7]);
return 0;
}
{0}
is valid only as an aggregate (array or struct
) initializer. {0}
仅作为聚合(数组或struct
)初始值设定项有效。
int roll_id[10] = {0}; /* OK */
roll_id[0] = 5; /* OK */
int roll_id[10] = 5; /* error */
roll_id[0] = {0}; /* error */
What you seem to want is to initialize p
of type struct student
. 你似乎想要的是初始化类型
struct student
p
。 That is done with a nested initializer. 这是通过嵌套的初始化程序完成的。
student p = { {0} }; /* initialize the array inside the struct */
I can see two errors in your code 我可以在你的代码中看到两个错误
#include<stdio.h>
typedef struct student
{
int roll_id[10];
} student;
int main()
{
student p;
student *pptr=&p;
pptr->roll_id[10]={0}; // in this line it should be pptr->roll_id[9]=0;
printf (" %d\n", pptr->roll_id[7]);
return 0;
}
as the length of array is 10 so the index should be 9 and u can use {0} only at the initialization of an array. 因为数组的长度是10所以索引应该是9,你只能在数组的初始化时使用{0}。
use as below for single array element initialization: 使用如下单数组元素初始化:
pptr->roll_id[x] = 8 ; // here x is the which element you want to initialize.
use as below for entire array initialization: 使用如下进行整个数组初始化:
student p[] = {{10, 20, 30}};//just example for size 3.
student *pptr = p;
for (i = 0 ; i < 3; i++)
printf ("%d\n", pptr->roll_id[i]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.