C Structures Introduction
In this page:
What is a Structure?
Unlike an array, which requires every element to be the same type, a structure can mix an int, a float, and a char array together in one logical unit -- ideal for modeling something like a student record with a name, age, and GPA.
Example: What is a Structure?
#include <stdio.h>
struct Student {
int age;
float gpa;
char grade;
};
int main() {
struct Student s = {20, 3.5f, 'A'};
printf("%d %.1f %c", s.age, s.gpa, s.grade);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Defining a Structure
The members you list inside the braces become the structure's blueprint -- no memory is actually allocated until you declare a variable of that structure type, similar to how declaring a class doesn't create an object.
Example: Defining a Structure
#include <stdio.h>
struct Point {
int x;
int y;
};
int main() {
struct Point p;
p.x = 3;
p.y = 4;
printf("%d %d", p.x, p.y);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Declaring Structure Variables
This two-step process (define the struct, then declare a variable of it) can be combined into a single statement, but writing them separately often makes larger programs easier to follow, especially when a struct is defined in a header file.
Example: Declaring Structure Variables
#include <stdio.h>
struct Point {
int x;
int y;
};
int main() {
struct Point p1;
p1.x = 1;
p1.y = 2;
printf("%d %d", p1.x, p1.y);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Accessing Structure Members
student.age = 20 both reads and writes the age field exactly like a normal variable -- the dot operator is what ties a specific member name to a specific structure variable in memory.
Example: Accessing Structure Members
#include <stdio.h>
struct Student {
int age;
};
int main() {
struct Student student;
student.age = 20;
printf("%d", student.age);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Array of Structures
This is the natural way to model a list of structured records, like a roster of students, since each array element is a full independent copy of the structure with its own set of member values.
Example: Array of Structures
#include <stdio.h>
struct Student {
int age;
};
int main() {
struct Student roster[2] = {{20}, {21}};
printf("%d %d", roster[0].age, roster[1].age);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: