In this tutorial you will learn about C Programming – Structures and Unions, initializing structure, assigning values to members, functions and structures, passing structure to functions, passing entire function to functions, arrays of structure, structure within a structure and union.
Structures are slightly different from the variable types you have been using till now. Structures are data types by themselves. When you define a structure or union, you are creating a custom data type.
Structures
Structures in C are used to encapsulate, or group together different data into one object. You can define a Structure as shown below:
struct object {
char id[20];
int xpos;
int ypos;
};
Structures can group data of different types as you can see in the example of a game object for a video game. The variables you declare inside the structure are called data members.
Initializing a Structure
Structure members can be initialized when you declare a variable of your structure:
struct object player1 = {“player1”, 0, 0};
The above declaration will create a struct object called player1 with an id equal to “player1”, xpos equal to 0, and ypos equal to 0.
To access the members of a structure, you use the “.” (scope resolution) operator. Shown below is an example of how you can accomplish initialization by assigning values using the scope resolution operator:
struct object player1;
player1.id = “player1”;
player1.xpos = 0;
player1.ypos = 0;
Functions and Structures
Since structures are of custom data types, functions can return structures and also take them as arguments. Keep in mind that when you do this, you are making a copy of the structure and all it’s members so it can be quite memory intensive.
To return a structure from a function declare the function to be of the structure type you want to return. In our case a function to initialize our object structure might look like this:
struct object createobj(char id[], int xpos, int ypos) {
struct object newobj;
strcpy(newobj.id, name);
newobj.xpos = xpos;
newobj.ypos = ypos;
return newobj;
}
Pass Structure to a Function
Let us now learn to pass a structure to a function. As an example let us use a function that prints members of the structure passed to it:
void printobj(struct object obj) {
printf(“name: %s, ”, obj.id);
printf(“x position: %d, ”, obj.xpos);
printf(“y position: %d”, obj.ypos);
printf(“\n”);
}
For completeness we shall include the full source of the above examples so you may see how it all fits together.
object1.c:
#include <stdio.h>
#include <stdlib.h>
struct object {
char id[20];
int xpos;
int ypos;
};
struct object createobj(char id[], int xpos, int ypos);
void printobj(struct object obj);
void main() {
struct object player1 = createobj("player1", 0, 0);
struct object enemy1 = createobj("enemy1", 2, 3);
printobj(player1);
printobj(enemy1);
}
struct object createobj(char id[], int xpos, int ypos) {
struct object newobj;
strcpy(newobj.id, id);
newobj.xpos = xpos;
newobj.ypos = ypos;
return newobj;
}
void printobj(struct object obj) {
printf("name: %s, ", obj.id);
printf("x position: %d, ", obj.xpos);
printf("y position: %d", obj.ypos);
printf("\n");
}
Here is what the output looks like:
Arrays of Structure
Since structures are data types that are especially useful for creating collection items, why not make a collection of them using an array? Let us now modify our above example object1.c to use an array of structures rather than individual ones.
object2.c:
#include <stdio.h>
#include <stdlib.h>
struct object {
char id[20];
int xpos;
int ypos;
};
struct object createobj(char id[], int xpos, int ypos);
void printobj(struct object obj);
void main() {
int i;
struct object gameobjs[2];
gameobjs[0] = createobj("player1", 0, 0);
gameobjs[1] = createobj("enemy1", 2, 3);
for (i = 0; i < 2; i++)
printobj(gameobjs[i]);
//update enemy1 position
gameobjs[1].xpos = 1;
gameobjs[1].ypos = 2;
for (i = 0; i < 2; i++)
printobj(gameobjs[i]);
}
struct object createobj(char id[], int xpos, int ypos) {
struct object newobj;
strcpy(newobj.id, id);
newobj.xpos = xpos;
newobj.ypos = ypos;
return newobj;
}
void printobj(struct object obj) {
printf("name: %s, ", obj.id);
printf("x position: %d, ", obj.xpos);
printf("y position: %d", obj.ypos);
printf("\n");
}
We create an array of structures called gamobjs and use the createobj function to initilize it’s elements. You can observer that there is not much difference between the two programs. We added an update for the enemy1’s position to show how to access a structure’s members when it is an element within an array.
Here is the output for this version:
Structure within a Structure
Structures may even have structures as members. Imagine our x, y coordinate pair is a structure called coordinates. We can redeclare our object structure as follows:
struct object {
char id[20];
struct coordinates loc;
};
You can still initialize these by using nested braces, like so:
struct object player1 = {“player1”, {0, 0}};
To access or set members of the above internal structure you would do like this:
struct object player1;
player1.id = “player1”;
player1.loc.xpos = 0;
player1.loc.ypos = 0;
You simply add one more level of scope resolution.
Unions
Unions and Structures are identical in all ways, except for one very important aspect. Only one element in the union may have a value set at any given time. Everything we have shown you for structures will work for unions, except for setting more than one of its members at a time. Unions are mainly used to conserve memory. While each member within a structure is assigned its own unique storage area, the members that compose a union share the common storage area within the memory. Unions are useful for application involving multiple members where values are not assigned to all the members at any one time.
Let us modify our structure object from above so that it has a union for indicating dead or alive in it:
struct object {
char id[20];
struct coordinates loc;
union deadoralive {
int alive;
int dead;
}
};
Only dead or alive can be set to anything at any one time. You can get to it the same as with a structure inside a structure as we learned in the last section.