An array or a variable can store elements of same data type, but they cannot store data of multiple data types. C programming language provides with a user-defined data type called a Structure.
Structure Definition
“A structure is a group of different data types which may or may not be the same.”
Declaring a Structure
Suppose you declared three different arrays as follows.
int arr1[20];
char arr2[20];
float arr3[20];
There is no relation between these three arrays and you cannot establish one. To solve the above problem, C programming language offers a user-defined data type called a Structure.
The syntax for declaring a Structure is given below.
struct {
< data_type 1>
< data_type 2>
< data_type 3>
.....................
.....................
};
For example, to declare a structure for a book.
struct book{
int Id;
char name[10];
float price;
};
The structure name is the book and it has three different variables of three different data types – integer,
character and float point.
The Id store the unique identification number of the book, the name stores the name of the book and the price stores the price value of the book.
Creating Structure Objects
After declaring the structure, you need to create objects of the declared structure. There are two popular methods in the C programming language to create structure objects.
Method 1
To create objects separately after declaration use following syntax.
struct < structure_name > < object_name >, < object_name >, < object_name> .... ;
For example, consider the following declaration
struct book obj1, obj2, obj3;
You just created three structure objects of type book;
Method 2
The second method creates an object at the time of the structure declaration itself.
struct book{
int Id;
char name[10];
float price;
} item1, item2;
In the above method, we have declared two objects – item 1 and item 2 of type book during the structure declaration. Note that the structure declaration ends with a semi-colon.
Initializing a Structure Object
The structure does not reserve any memory when you declare it. You must initialize the structure members to reserve the memory space for the structure. The total size of the structure depends on the size of its individual members.
You can check this using a small program given below.
Example #1
#include <stdio.h>
struct cars{
int ID;
char name;
int price;
};
int main() {
/* create two objects of type struct cars */
struct cars c1, c2;
printf("Size of Cars = %d\n ",sizeof(c1));
system(" pause ");
return 0;
}
Output
The output of above is as follows.
Size of Cars = 12
Press any key to continue . . .
Now, we will change the data type for member variable price, so that the size of the structure object increases. The modified program will have the following codes,
Example #2
#include <stdio.h>
struct cars{
int ID;
char model;
double price;
};
int main()
{
/* create two objects of type struct cars */
struct cars c1, c2;
printf("Size of Cars = %d\n", sizeof(c1));
system("PAUSE");
return 0;
}
Output
The output of the modified program shows an increase in the size of the structure because the double data type takes 8 bytes of memory space including some extra space. This results in the increment of the overall size of the structure.
Size of Cars = 16
Press any key to continue . . .
To initialize a structure object you need to assign values to its variables. You can do this in two ways.
Method 1
Assign at the time of creation. You can assign the initial value to the member at the time of creating the objects.
struct cars c1 = {2322, "Toyota", 230000.00};
You must assign the values in the correct order of structure members inside the brackets above.
Method 2
In this method, you assign values to each and every member individually. For Example,
c1.id = 333;
c1.model = "Toyota";
c1.price = 2300000.00;
The above method is inefficient when you have to do this for a large number of structure objects.
Accessing a Structure Variable
To access the structure member use the ‘dot’ operator. The syntax to use the variable is
For example,
c1.price;
Where c1 is the structure object and price is the structure member.
Memory Representation of Structure
Consider the following example of C structure.
Example #3
#include <stdio.h>
struct cars{
int ID;
char model;
double price;
};
int main()
{
/* create two objects of type struct cars */
struct cars c1, c2;
c1.ID = 333;
c1.model = 'N';
c1.price = 24400.00;
printf(" Size of the Structure = %d\n",sizeof(c1));
for(i=0;i < 30;i++)
printf("_");printf("\n\n");
printf( "id= %u\t model = %u\t price = %u\n",&c1.ID, &c1.model, &c1.price);
system("PAUSE");
return 0;
}
Output
The output of the above program shows that the member variables of a structure are stored sequentially. First the integer took 4 bytes, then character takes 1-byte storage and finally, double took 8 bytes of information.
The memory representation of a structure is given below. The structure member variables are stored sequentially.
Array of Structures
You can also create an array of structures. A single object of a structure consumes a lot of memory. So you must carefully decide the total size of an array of structures.
Also, an array does not use dynamic memory, if you don’t use the array properly, the allocated memory is wasted.
After declaring the array of structure, you may run out of memory for other variables and computations in the C program.
Declaring an Array of Structures
The declaration is very simple, and it is the same as declaring a normal one-dimensional array except the data type in a structure is heterogeneous.
struct < struct_array > [size];
For example,
struct cars [50];
Accessing a Member of an Array of Structures
You can access any member of the array of the structure just like an ordinary array. The syntax to access a member of the array of structure and its member is given below.
< struct_array_name > [index_value];
For example,
cars[10];
The syntax to access a member of the above structure is as follows.
[index_value].< member_name> ;
For example,
cars[10].price = 100.333;
Copying all Members of a Structure to Another Structure of the Same Type.
Unlike a normal array, you can directly copy values of all member of a structure to another structure of the same type. You should focus on the word – directly. In an array, the direct copy does not work. To copy an entire array to another array, you must go through a loop and copy each element one at a time.
For example,
for(i=0;i < 10 ; i++)
{
c[i] = a[i];
}
where c[i] and a[i] are arrays of same type and size;
However, with the structure, you can copy them directly. Consider the following example.
Example #4
#include <stdio.h>
#include<stdlib.h>
/* declaring the structure one */
struct school
{
char section;
int students;
int teachers;
};
int main()
{
struct school universal[10];
int i,n;
universal[0].section = 'A';
universal[0].students = 100;
universal[0].teachers = 25;
/* copy the entire structure to new structure of same type */
universal[5] = universal[0];
/* print the new structure */
printf( "Section = %c\n",universal[5].section);
printf( "Students = %d\n",universal[5].students);
printf( "Teachers = %d\n",universal[5].teachers);
system("PAUSE");
return 0;
}
Output
The output of the above program shows that the entire content of structure universal [0]
is copied to universal [5]
directly.
Nested Structures
C programming structures can be nested within another structure. There is no limit on the level of nesting as long as you are not out of memory.
For example,
struct Sports {
struct Game {
int Id;
char name;
int players;
};
int number_of _events:
int event_manager;
};
In this way, you can achieve multiple levels of nesting for a given C structure.
Union
A union has the same form and rules as a Structure except for the implementation. Inside memory, only one field from a union is used at a time. Basically, the size of a union depends on the size of its largest data type.
For example, suppose you are given a union as the following,
Example #5
#include <stdio.h>
union book
{
int name;
int id;
double price;
} b1;
int main()
{
printf("The Size of the Union = %d Bytes\n",sizeof(b1));
system("PAUSE");
return 0;
}
Output
The output of the program is the byte size of the given union and its equal to the byte size of its largest member variable which is double.
The Size of the Union = 8 Bytes
References
- Balagurusamy, E. 2000. Programming in ANSI C. Tata McGraw-Hill Education,
- Brian W. Kernighan, Dennis M. Ritchie. 1988. C Programming Language, 2nd Edition. Prentice Hall.