The short answer
Can you use structs in C? Yes. Structs are a standard part of C. A struct groups several named fields, which can have different types, into one new type. You create variables of that type and read or write each field with the dot operator.
Defining and using a struct
#include <stdio.h>
struct Point {
int x;
int y;
};
int main(void) {
struct Point p = {3, 4};
p.x = p.x + 1;
printf("(%d, %d)\n", p.x, p.y);
return 0;
}
The program prints (4, 4). The struct Point { ... }; part defines the type, and the semicolon after the closing brace is required. struct Point p creates a variable of that type, and its fields are read and written with p.x and p.y.
C99 and later also let you name the fields when you initialize them, as in struct Point q = { .y = 4, .x = 3 };. The details are in c designated initializers.
Shortening the name with typedef
In C, you write struct Point each time you use the type. A typedef gives the type a shorter name:
typedef struct {
int x;
int y;
} Point;
Point p = {3, 4};
After this, Point works without the struct keyword. The tag name is optional when you use this form.
Passing a struct to a function
Passing a struct by value gives the function a copy. Passing a pointer lets the function change the original:
void move_right(struct Point *p, int dx) {
p->x += dx;
}
Call it with the address of the variable, as in move_right(&p, 2);. The arrow operator -> reads a field through a pointer.
What C structs cannot do
C structs hold data only. Compared with C++ structs, they do not have:
- member functions, so functions live outside the struct and take it as an argument, as
move_rightdoes - access labels, so any code that can see the variable can read and write every field
- inheritance
- constructors, so you set starting values with braces or assignments
Arrays of structs
An array of structs in C works like any other array. This declares three points:
struct Point points[3];
Each element is a complete struct, so points[0].x reads the x field of the first point.
Structs in C++
In C++, a struct can also have member functions, access labels and constructors. The comparison with classes is in c struct vs class.