Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Properly use Array of Structures of C

I’m recently started learning about structures in C Language. I tried out a sample program to extend my learning curve. But, here in this subject, I’m facing few errors. Shall anyone please figure out the errors in the following program.

#include<stdio.h>
main() {
 int i;
 struct elements {
  int z; /* Atomic Number */
  float m; /* Mass Number */
  char *name;
  char *symbol;
 };
 struct elements e[5];
 e[0] = (struct elements){1,1.008,"Hydrogen","H"};
 e[1] = (struct elements){2,4.0026,"Helium","He"};
 e[2] = (struct elements){3,6.94,"Lithium","Li"};
 clrscr();
 for(i=0;i<3;i++) {
  printf("Element Name: %s\n",e[i].name);
  printf("Symbol: %s\n",e[i].symbol);
  printf("Atomic Number: %d\n",e[i].z);
  printf("Atomic Mass: %0.2f\n",e[i].m);
 }
 getch();
 return 0;
}

This shows the following Error messages:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Despite the other comments, if this is what you have to work with, then you’ll still be wanting a solution.

Try:

struct elements e[5] = {
    {1,1.008,"Hydrogen","H"},
    {2,4.0026,"Helium","He"},
    {3,6.94,"Lithium","Li"}
 };

What you had would work on later compilers (although some will want char const * in the struct for name and symbol to accept string literals), but its actually not very pretty to read, nor is it necessary when you are defining the entire array.

If you do this, you can omit the array size (change [5] to []) and it will size according to the number of elements provided.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading