Defining Struture in C
Declaring a Structure
struct structure_name;
- This is just a declaration of the structure type, which tells the compiler that a structure with that name exists. It doesn't actually allocate any memory for the structure.
Defining a Structure
struct structure_name {
data_type member1;
data_type member2;
...
data_type memberN;
};
- This defines the structure type by specifying the name of the structure and its member variables, each of which has its own data type.
For example:
Let's define a simple structure for a point in two-dimensional space, with an x and y coordinate:
struct point {
int x;
int y;
};
This code defines a structure type called point, which has two member variables of type int called
x
andy
.Once you have declared and defined a structure type, you can create variables of that type, as shown in the following example. This code creates a variable called p of type point.
struct point p;
- You can also initialize the member variables of a structure variable at the time of declaration, like this:
struct point p = {10, 20};
This code creates a variable called p
of type point and initializes its x
and y
member variables to 10 and 20, respectively.
Example
This program shows how to declare, define, and create an instance of a structure:
#include <stdio.h>
// Declare the structure type
struct point
{
int x;
int y;
};
int main()
{
// Define a variable of the structure type
struct point p;
// Assign values to the structure members
p.x = 10;
p.y = 20;
// Print out the values of the structure members
printf("x = %d, y = %d\n", p.x, p.y);
return 0;
}
Output:
Explanation
- We first declare the
point
structure type, which has two member variables of type int calledx
andy
. - We then define a variable of the structure type called p in the main() function.
- We assign values to the
x
andy
members of thep
structure variable using the dot(.)
operator to access the members. - Finally, we print out the values of the
x
andy
members usingprintf()
.
Output:
x = 10, y = 20