Search code examples
cstructdeclarationdefinitionincomplete-type

How to use structures in C ? I am finding it difficult to understand getting a lot of error while implementing it


I am trying to implement a structure in C. I'm getting these errors.

Please help me with this error and also explain to me what am I doing wrong.

main.c:7:12: error: variable ‘s1’ has initializer but incomplete type
    7 |     struct student s1 = {"Nick",16,50,72.5};
      |            ^~~~~~~
main.c:7:26: warning: excess elements in struct initializer
    7 |     struct student s1 = {"Nick",16,50,72.5};
      |                          ^~~~~~
main.c:7:26: note: (near initialization for ‘s1’)
main.c:7:33: warning: excess elements in struct initializer
    7 |     struct student s1 = {"Nick",16,50,72.5};
      |                                 ^~
main.c:7:33: note: (near initialization for ‘s1’)
main.c:7:36: warning: excess elements in struct initializer
    7 |     struct student s1 = {"Nick",16,50,72.5};
      |                                    ^~
main.c:7:36: note: (near initialization for ‘s1’)
main.c:7:39: warning: excess elements in struct initializer
    7 |     struct student s1 = {"Nick",16,50,72.5};
      |                                       ^~~~
main.c:7:39: note: (near initialization for ‘s1’)
main.c:7:20: error: storage size of ‘s1’ isn’t known
    7 |     struct student s1 = {"Nick",16,50,72.5};

My code

#include<stdio.h>
#include<stdlib.h>

int main()
{
     
    struct student s1 = {"Nick",16,50,72.5};
    
    printf("%s",s1.name);
    
   // return 0;
}

struct student{
    
    char name[4];
    
    int age;
    
    int roll_no;
    
    float marks;
}s1;

Solution

  • In the point of this declaration

    struct student s1 = {"Nick",16,50,72.5};
    

    the compiler do not know how the structure is defined and what data members it has. So it issues the messages.

    You need to place the structure definition before declaring an object of the structure type. For example

    struct student{
        
        char name[4];
        
        int age;
        
        int roll_no;
        
        float marks;
    };
    
    int main( void )
    {
        struct student s1 = {"Nick",16,50,72.5};
        //...
    

    Pay attention to that you are trying to declare two objects with the name s1 of the structure type.

    The first one is declared in main

    struct student s1 = {"Nick",16,50,72.5};
    

    and the second one in the file scope after main

    struct student{
        
        char name[4];
        
        int age;
        
        int roll_no;
        
        float marks;
    }s1;
    

    Remove this declaration in the file scope and place the structure definition before main as it was shown above.