Here is a simple C programs in structure but i dont quite get what am i doing wrong as the output is not what i desired ,
P1
#include<stdio.h>
struct book
{
char name[10];
char author[10];
int refno;
};
//passing whole structure variable
void display(struct book b)
{
printf("%s %s %d",b.name,b.author,b.refno);
}
int main()
{
struct book b1={"LET US C","YPK",25};
display(b1);
}
Here this one works completely fine with output:
LET US C YPK 25
--------------------------------
Process exited after 0.3952 seconds with return value 0
Press any key to continue . . .
BUT if i try
struct{
// element -1;
//element -2;
//element-3;
}b1;
/*then*/
int main()
{
b1={"LET US C","YPK",25};
display(b1);
It shows error messages:-
1:[Warning] extended initializer lists only available with -std=c 11 or -std=gnu 11
2:[Error] no match for 'operator=' (operand types are 'book' and '<brace-enclosed initializer list>')
3:[Note] candidate is:
4:[Note] book& book::operator=(const book&)
5:[Note] no known conversion for argument 1 from '<brace-enclosed initializer list>' to 'const book&'
The same messsages are shown if i try :
struct book
{
//elements declarations as p1
}b[10];
int main()
{
b[1]={"LET US C","YPK",25};
display(b[1]);
}
OR WITH
struct book
{
//elements declarations as p1
};
int main()
{
struct book b[10];
b[1]={"LET US C","YPK",25};
display(b[1]);
}
So whats the problem?
and actually my main objective was to define array of structure, as in second last and last method but it does not seem to work so please help>
CodePudding user response:
In C, the syntax {elem1, elem2, elem3, ...}
is only valid if you are initializing a structure (or an array) not assigning one. That's why it doesn't work in your example.
When you write b[1]={"LET US C","YPK",25};
you are trying to assign a value not initializing one.
For short:
Initializing is when you give a value to a variable that you are creating at the moment
Assigning is when you give a value to a variable already created.
For you example to work you can write this
struct book
{
char name[10];
char author[10];
int refno;
};
int main()
{
struct book b[10];
b[1]=(struct book){"LET US C","YPK",25};
^^^^^^^^^^^^
display(b[1]);
}
Now, you can declare structure variable anywhere, either right after structure declaration or anywhere in the main function but the point to be noted is when you are defining/assigning any of the variable i have used
(struct book)
on the right hand side of assignment operator which helps compiler to understand that b[1]
variable belongs to struct book data type, which corrects the error present in the program.
This feature of C language is known as compound literal.