Search code examples
arrayscstructure

Assigning values to an array Structure member


I have created a C structure as follows,

struct student{
int regNo;
char *name;
int age;
int marks[5]; 
};

Then I created a student object as S1 and tried to assign values to the structure members one by one.

struct student s1;
s1.regNo= 2312;
s1.name = "Andrew";
s1.age = 20;
s1.marks[5] = { 90,89,70,58,88};

But when I give values to the int array of marks it gives me a compile error as,

3.c: In function 'main':
3.c:18:16: error: expected expression before '{' token
s1.marks[] = { 90,89,70,58,88};

But when I tried assigning values to each index separately,

s1.marks[0] = 90;
s1.marks[1] = 89;
s1.marks[2] = 70;
s1.marks[3] = 58;
s1.marks[4] = 88;

the issue was solved.

Can I please know what I have done wrong in the 1st attempt, where I assigned values to the array in one go ?


Solution

  • {90,89,70,58,88} is an example of an array initialiser. It is valid only when the variable is declared, e.g. the following is valid.

    int array[5] = {90,89,70,58,88};
    

    But this is not:

    int array[5];
    array = {90,89,70,58,88};