数组初始化

时间:2013-01-07 09:46:52

标签: c arrays

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

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

3 个答案:

答案 0 :(得分: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 */

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

student p = { {0} }; /* initialize the array inside the struct */

答案 1 :(得分: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}。

答案 2 :(得分: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]);