C Syntax of struct
C Syntax of struct
In the C programming language, a struct is a user-defined data type that allows you to combine different types of variables into a single entity. It is used to create a composite data structure that can hold multiple pieces of related information.
The syntax for defining a struct in C is as follows:
struct struct_name {
data_type1 member1;
data_type2 member2;
// ...
};
struct_name
is the name of the struct type.data_type1
,data_type2
, etc., are the data types of the members.member1
,member2
, etc., are the names of the members.
Here's an example of a struct definition:
struct Person {
char name[50];
int age;
float height;
};
In this example, we define a struct named Person
with three members: name
, age
, and height
. The name
member is an array of characters, age
is an integer, and height
is a floating-point number.
To declare a variable of the struct type, you can use the following syntax:
struct struct_name variable_name;
For example:
struct Person person1;
To access the members of a struct variable, you use the dot (.
) operator. For example, to assign a value to the name
member of person1
, you can do:
strcpy(person1.name, "John");
To access the value of a struct member, you can use the dot operator as well. For example, to print the value of the age
member of person1
, you can do:
printf("Age: %d\n", person1.age);
Structs can also be used as members of other structs, allowing you to create nested data structures.
That's the basic syntax of a struct in C. It provides a way to define custom data types that can hold multiple related pieces of information.