简体   繁体   中英

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.

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 . 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.

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM