C: Structures
Arrays are useful in storing datas of the same type. However, we may also need to group related datas of different types together. For example, consider grouping together the particulars of a movie. Storing its title, runtime and IMDb rating would require the variables to be of type char
, unsigned int
and float
respectively, involving several data types. C language supports such aggregation of dissimilar basic data types as a single object, known as structures.
Defining a structure in C starts with the keyword struct
, followed by a given name and a pair of curly braces inside which are data fields known as elements or members. Here we define a structure named movie
with three members: title
, runtime
and imdb
struct movie {
char title[50];
unsigned runtime;
float imdb;
}
Character arrays inside struct
need to be of a specified size and cannot be flexible. Hence, declaring the first member as char title[]
without specifying the size would have thrown an error.
Next, we declare a structure variable called m
struct movie {
char title[50];
unsigned runtime;
float imdb;
};
struct movie m;
Assigning Values to Structure Elements
Assigning and accessing values of the members of a structure variable can be achieved using the dot (.
) operator. For example, m.title
represents the title of the m
structure variable. In this example, we consider the movie Sky Captain and the World of Tomorrow which runs for 107 minutes and has an IMDb rating of 6.1 and assign its particulars as shown below. The last printf()
statement prints the assigned values
#include <stdio.h>
#include <string.h>
struct movie {
char title[50];
unsigned runtime;
float imdb;
};
struct movie m;
main() {
strcpy(m.title,"Sky Captain and the World of Tomorrow");
m.runtime = 107;
m.imdb = 6.1;
printf("%s %u %.1f", m.title, m.runtime , m.imdb);
}
The <string.h>
header file is included to make use of the strcpy()
function. The %.1f
format specifier in the last printf()
statement limits the output number to one decimal place.
Structure Initialization
We initialize a structure variable by enclosing the values in a pair of braces
#include <stdio.h>
struct movie {
char title[50];
unsigned runtime;
float imdb;
};
struct movie m = {"Sky Captain and the World of Tomorrow", 107, 6.1};
main() {
printf("%s %u %.1f", m.title, m.runtime , m.imdb);
}