Below is the general definition of a structure
struct structure_name{
type variable1;
type variable2;
---------------
---------------
};
struct - keyword
structure_name - tag
type - data type
variable1, variable2 - data members of the given structure
Consider the following example,
struct student {
int age;
char name[32];
};
Above is a definition of a structure named struct student.
Let us see how to declare structure variables. Structure variables can be declared while defining a structure or after structure definition.
Declaring structure variables at structure definition
struct student {
int age;
char name[32];
}obj1, obj2;
Here, obj1 and obj2 are structure variables of type struct student. And they are declared during structure definition.
Declaring structure variables after structure definition:
struct student {
int age;
char name[32];
};
struct student obj1, obj2;
Here, obj1 and obj2 are structure variables of type struct student. And they are declared after structure definition.
Consider the following example,
struct student {
int age;
char name[32];
};
Above is a definition of a structure named struct student.
Let us see how to declare structure variables. Structure variables can be declared while defining a structure or after structure definition.
Declaring structure variables at structure definition
struct student {
int age;
char name[32];
}obj1, obj2;
Here, obj1 and obj2 are structure variables of type struct student. And they are declared during structure definition.
Declaring structure variables after structure definition:
struct student {
int age;
char name[32];
};
struct student obj1, obj2;
Here, obj1 and obj2 are structure variables of type struct student. And they are declared after structure definition.
Example:
#include <stdio.h>
struct student {
char name[100];
int rank;
}obj = {"jp", 1};
int main() {
// struct student obj = {"jp", 1};
printf("Name: %s\n", obj.name);
printf("Rank: %d\n", obj.rank);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Name: jp
Rank:1
Name: jp
Rank:1
No comments:
Post a Comment