0

Why is not printing names ??

#include <stdio.h> #include <stdlib.h> #include <string.h> // The student structure union Student { char* name ; int roll_number; float marks; }; int main() { int i = 0, n = 5; union Student student[n]; //Students data student[0].name = "Kapil"; student[0].roll_number = 1; student[0].marks = 73.6; student[1].name = "Vikas"; student[1].roll_number = 2; student[1].marks = 78.3; student[2].name = "Ajay"; student[2].roll_number = 3; student[2].marks = 87.4; // Print the Students information printf("Student Details:\n\n"); for (i = 0; i < n; i++) { printf("\tName = %s\n", &student[i].name); printf("\tRoll Number = %d\n", &student[i].roll_number); printf("\tTotal Marks = %f\n\n", &student[i].marks); } return 0; }

30th Dec 2021, 2:56 PM
Mr. A
Mr. A - avatar
5 Answers
+ 4
You can't use a union. Unions only allow for one attribute to be held at one time. You can't assign all three cause each assigment will overwrite the last.
30th Dec 2021, 3:26 PM
Slick
Slick - avatar
+ 2
Use struct instead of union. And remove & in loop print statements.. printf("Student Details:\n\n"); for (i = 0; i < n; i++) { printf("\tName = %s\n", student[i].name); printf("\tRoll Number = %d\n", student[i].roll_number); printf("\tTotal Marks = %f\n\n", student[i].marks); } since you added only 3 values, use n=3
30th Dec 2021, 3:05 PM
Jayakrishna 🇼🇳
+ 1
Yes. Union only holds one last attribute value stored by overwriting..
30th Dec 2021, 3:38 PM
Jayakrishna 🇼🇳
0
Bro I want the using union
30th Dec 2021, 3:23 PM
Mr. A
Mr. A - avatar
0
So what should I do to print the data of three students using unions
30th Dec 2021, 3:51 PM
Mr. A
Mr. A - avatar