Table of Contents
In this tutorial, you’ll learn about C structure. You will learn how to define and use structures with the help of examples.
What is a structure?
A structure is a user-defined data type in C. A structure creates a data type that can be used to group items of possibly different types into a single type.
How to create a structure?
Before you can create structure variables, you need to define its data type. To define a struct, the struct
keyword is used.Following is the syntax
Syntax of struct
struct structureName
{
dataType member1;
dataType member2;
...
};
EXAMPLE
struct House
{
char Ownername[50];
int citNo;
double pincode;
};
Here, a derived type struct House
is defined. Now, you can create variables of this type.
How to declare structure variables?
A structure variable can either be declared with a structure declaration or as a separate declaration like basic types.
// A variable declaration with structure declaration.</strong>
struct Point
{
int x, y;
} p1; // The variable p1 is declared with 'Point'
// A variable declaration like basic data types</strong>
struct Point
{
int x, y;
};
int main()
{
struct Point p1; // The variable p1 is declared like a normal variable
}
In C, it is mandatory to use struct keyword before variable name.
How to initialize structure members?
Structure members cannot be initialized with the declaration. For example, the following C program fails in the compilation.
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
The reason for above error is simple, when a datatype is declared, no memory is allocated for it. Memory is allocated only when variables are created.
Structure members can be initialized using curly braces ‘{}’. For example, following is a valid initialization.
struct Point
{
int x, y;
};
int main()
{
// A valid initialization. member x gets value 0 and y
// gets value 1. The order of declaration is followed.
struct Point p1 = {0, 1};
}
How to access C structure elements?
There are two types of operators used for accessing members of a structure.
.
– Member operator->
– Structure pointer operator
Structure members are accessed using dot (.) operator.
EXAMPLE
include<stdio.h>
struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {0, 1};
// Accessing members of point p1
p1.x = 20;
printf ("x = %d, y = %d", p1.x, p1.y);
return 0;
}
OUTPUT
x = 20, y = 1
Keyword typedef
We use the typedef
keyword to create an alias name for data types. It is commonly used with structures to simplify the syntax of declaring variables.
This code
struct Distance{
int feet;
float inch;
};
int main() {
struct Distance d1, d2;
}
is equivalent to
typedef struct Distance{
int feet;
float inch;
} distances;
int main() {
distances d1, d2;
}
More on C structure
- C Nested Structure
- Structure and pointer
- Passing Structure to a pointer