I am getting an error while trying to compile this code.......tried different IDEs
#include<stdio.h>
#include<stdlib.h>
struct car{
int price[5];
}c1;
int main(){
c1.price[5]={10,20,30,40,50};
}
error:
7 14 D:\CODING\c programs\Struct.c [Error] expected expression before '{' token
CodePudding user response:
This isn't valid C. You can only statically initialize an array at definition time. Something like the following:
int price[5] = {10,20,30,40,50};
Otherwise, you must use subscripts to initialize the array:
c1.price[0] = 10;
c1.price[1] = 20;
c1.price[2] = 30;
c1.price[3] = 40;
c1.price[4] = 50;
Try to read the book 'The C Programming language by Ritchie & Kernighan' to get a feel for the language first.
CodePudding user response:
After this declaration
struct car{
int price[5];
}c1;
the object c1
with its data member are already created that is defined.
So in this statement
c1.price[5]={10,20,30,40,50};
you are trying to assign a braced list to the non-existent element of the array with the index equal to 5
.
Even if you will write instead
c1.price = {10,20,30,40,50};
nevertheless arrays do not have the assignment operator.
You can initialize the data member price
of the object c1
when the object is defined. For example
struct car{
int price[5];
}c1 = { .price={10,20,30,40,50} };
Otherwise to change values of the data member price you should use a loop as for example
for ( size_t i = 0; i < sizeof( c1.price ) / sizeof( *c1.price ); i )
{
c1.price[i] = ( int )( 10 * ( i 1 ) );
}