expected ';', identifier or '(' before 'struct'

61 Views Asked by At

Why I can't place struct student s; in that place?

This is the wrong code

#include<stdio.h>

struct student
{
    int num;
    char name[20];
    float mark;

}struct student s;

int main()
{
    scanf("%d%s%f",&s.num,s.name,&s.mark);
    struct student *ptr=&s;
    printf("%d\n",s.num);
    printf("%d\n",ptr->num);
    printf("%d",(*ptr).num);
    return 0;
}

This is the code without error

#include<stdio.h>

struct student
{
    int num;
    char name[20];
    float mark;

}


int main()
{
    struct student s;
    scanf("%d%s%f",&s.num,s.name,&s.mark);
    struct student *ptr=&s;
    printf("%d\n",s.num);
    printf("%d\n",ptr->num);
    printf("%d",(*ptr).num);
    return 0;
}

When I try to learn struct in c language, I stuck with this. I can uderstand what is the wrong in this code.I am just biginner to programming. Help me to find it

1

There are 1 best solutions below

2
Allan Wind On BEST ANSWER

C expects an optional identifier (variable name). You have two options:

  1. Specify an identifier:

    struct student
    {
        int num;
        char name[20];
        float mark; 
    } s;
    
  2. Leave out the identifier and define the variable separately:

    struct student
    {
        int num;
        char name[20];
        float mark; 
    };
    
    struct student s;
    

Prefer local to global variables. In your 2nd code example struct s is a local variable you are just missing a ; after the struct s definition.

Prefer local to global scope. If you only need struct s in main() declare it within that function.