About C Struct (Structure)
In C programming, a struct is a user-defined data type that is used to group variables of different types under a single name.
It is useful for organizing related data items into a single entity.
It makes code more readable and manageable when dealing with complex data types.
The 'struct' is the short for 'structure'.
Syntax of 'struct'
xxxxxxxxxx
//Defining a struct
struct StructName {
dataType member1;
dataType member2;
...
};
//Declaring Variables/object of a struct
struct StructName variableName;
-
struct StructName
: The 'struct' keyword defines the 'struct'. The 'StructName' is the name of the structure and it will be replaced by the user defined name. -
dataType member1;
: The 'dataType' is the data type of the member (variable) of structure and the 'member1' is name of the member (variable) of the structure. The 'member1' will be replaced by the user defined name. -
struct StructName variableName;
: The 'struct' is the keyword and 'StructName' is the name of the struct. 'StructName' will be followed by the 'variableName' and it will be replaced by the user defined variable name.
Create a 'struct'
A 'struct' and it object have been created in the following example:
Example of Creating a Struct
xxxxxxxxxx
#include <stdio.h>
#include <string.h> // This directive is used for 'strcpy' function
//Defining a struct
struct Person {
char name[50];
int age;
};
int main() {
//Declaring variable of Person Struct
struct Person personObj;
//Initializing member variables of personObj
strcpy(personObj.name, "John");
personObj.age = 30;
// Access and print members of personObj
printf("%s\n", personObj.name);
printf("%d\n", personObj.age);
return 0;
}
Output of the above example
John 30
Explanation of code:
-
struct Person { char name[50]; int age;};
: This defines a struct name 'Person'. The 'Person' struct has two members: 'name' and 'age'. -
struct Person personObj;
: This declares a variable of Person Struct named 'personObj'. -
strcpy(personObj.name, "John");
: This initializes the 'personObj' member 'name' with value "John". The 'strcpy' function is used to assign the value "John" to 'personObj.name' member by copying. -
personObj.age = 30;
: This initializes the 'personObj' member 'age' with value 30. -
printf("%s\n", personObj.name);
andprintf("%d\n", personObj.age);
: These are used to access members of 'personObj' and print their vaules. - Please note that to access a member of struct a period (.) is used between variable (object) of struct and its member.