Search code examples
arrayscdata-structuresstructstructure

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


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 it this way, you can omit the array size (change [5] to []) and it will size according to the number of elements provided.