I am a beginner in C programming. I did a simple structure program. I tried to assign the value of one structure variable to another structure variable. If I define inside main(), it doesn't give an error.
This works fine.
#include<stdio.h>
#include <string.h>
struct student{
char name[50];
int age;
int roll;
float marks;
};
int main(){
struct student s1 = {"Nick",21,3,12.41};
struct student s2, s3;
strcpy(s1.name,s2.name);
s2.age = s1.age;
s2.roll = s1.roll;
s2.marks = s1.marks;
s3 = s2;
printf ( "\n%s %d %d %f", s1.name, s1.age, s1.roll, s1.marks ) ;
printf ( "\n%s %d %d %f", s2.name, s2.age, s2.roll, s2.marks ) ;
printf ( "\n%s %d %d %f", s3.name, s3.age, s3.roll, s3.marks) ;
}
But if I assign it outside main(), it throws error. what is the difference?
#include<stdio.h>
#include <string.h>
// USE ASSIGNMENT OPERATOR "=" TO ASSIGN VALUES OF STRUCT
struct student{
char name[50];
int age;
int roll;
float marks;
};
#why throwing an error?
struct student s1 = {"Nick",21,3,12.41};
struct student s2, s3;
strcpy(s1.name,s2.name);
s2.age = s1.age;
s2.roll = s1.roll;
s2.marks = s1.marks;
s3 = s2;
int main(){
printf ( "\n%s %d %d %f", s1.name, s1.age, s1.roll, s1.marks ) ;
printf ( "\n%s %d %d %f", s2.name, s2.age, s2.roll, s2.marks ) ;
printf ( "\n%s %d %d %f", s3.name, s3.age, s3.roll, s3.marks) ;
}
Is there any rule that struct variable has to be defined inside main()?