A struct lets you group related values, such as the x and y coordinates of a point, under one type name. This guide covers how to define a struct in C, create variables of that type, set its members and read them back. If you have asked “Can you use structs in C?”, the answer is yes. C has structs, but it does not have constructors, which is one of the main differences from C++.
Define the struct
You define a struct with the struct keyword, list its members and end the definition with a semicolon:
struct Point {
int x;
int y;
};
This definition creates a new type called struct Point. It does not create a variable yet. Forgetting the semicolon after the closing brace is a common mistake, and the compiler error often shows up on a later line.
Create and initialize a variable
Declare a variable of the new type and give it values in braces:
struct Point p1 = {3, 4}; // x is 3, y is 4
The values are assigned to the members in declaration order. If you give fewer values than there are members, the rest are set to zero:
struct Point p2 = {3}; // x is 3, y is 0
In C, the struct keyword is part of the type name, so Point p1; is an error unless you add a typedef, which is covered below.
Read and change members
Use the dot operator with a variable and the arrow operator with a pointer to the struct:
p1.x = 10;
struct Point *ptr = &p1;
ptr->y = 7; // same as (*ptr).y = 7;
Designated initializers
C99 added designated initializers, which name each member you set:
struct Point p3 = {.y = 8, .x = 2}; // x is 2, y is 8
In C, named members can appear in any order, and any members you leave out are set to zero.
Use a typedef to shorten the name
A typedef lets you write Point instead of struct Point:
typedef struct Point {
int x;
int y;
} Point;
Point p4 = {5, 6};
Set members with a function
C has no constructors, so a common pattern is a function that fills in a struct passed by pointer:
void point_init(struct Point *p, int x, int y) {
p->x = x;
p->y = y;
}
Call it with the address of a variable, as in point_init(&p1, 3, 4);.
A complete program
This program defines the struct, creates a variable, changes one member and prints both members:
#include <stdio.h>
struct Point {
int x;
int y;
};
int main(void) {
struct Point p = {3, 4};
p.x = 10;
printf("%d, %d\n", p.x, p.y); // prints 10, 4
return 0;
}
The same struct in C++
C++ accepts the same definition and the same initialization. The difference is that the struct keyword is optional when you use the name, so Point p = {3, 4}; works without it. C++ structs can also have constructors, which C does not allow. The rules are covered in c struct constructor.
Common mistakes
- Leaving out
structin C, as inPoint p;, when there is no typedef. The compiler reports an unknown type name. - Forgetting the semicolon after the closing brace of the definition.
- Reading the members of a local struct that you never set. Without an initializer, their values are unknown.