Swetha.P
Swetha.P

Reputation: 89

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

Upvotes: 2

Views: 199

Answers (3)

nagaradderKantesh
nagaradderKantesh

Reputation: 1690

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

Upvotes: 0

Tushar Mishra
Tushar Mishra

Reputation: 177

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.

Upvotes: 0

Potatoswatter
Potatoswatter

Reputation: 137810

{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 */

Upvotes: 4

Related Questions