1

根据建议,我已经修改了代码,但是如何初始化结构中的单个元素?

#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;
}
4

3 回答 3

4

{0}仅作为聚合(数组或struct)初始化程序有效。

int roll_id[10] = {0}; /* OK */
roll_id[0] = 5; /* OK */

int roll_id[10] = 5; /* error */
roll_id[0] = {0}; /* error */

您似乎想要的是初始化ptype struct student。这是通过嵌套的初始化程序完成的。

student p = { {0} }; /* initialize the array inside the struct */
于 2013-01-07T09:49:09.160 回答
0

我可以在您的代码中看到两个错误

    #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;
    }

由于数组的长度为 10,因此索引应为 9,并且您只能在数组初始化时使用 {0}。

于 2013-01-07T09:53:38.010 回答
0

如下用于单个数组元素初始化:

 pptr->roll_id[x] = 8 ; // here x is the which element you want to initialize.

如下用于整个数组初始化:

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]);
于 2013-01-07T12:16:45.320 回答