← The C Language
Lesson 39 of 77 · 10 XP
Structs
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A struct combines several values of different types under one name. It's the closest relative of a class from other languages, just without methods:
struct point {
int x;
int y;
};
struct point p = {3, 4}; // initialisation in order
struct point q = {.y = 1, .x = 2}; // by field names (C99)
p.x = 10; // access a field with a dot
printf("(%d, %d)\n", p.x, p.y);
Structs can be assigned (q = p; copies all the fields), passed to functions and returned from them. You can't compare them with ==: the fields are compared one by one.
struct point add(struct point a, struct point b)
{
struct point r = {a.x + b.x, a.y + b.y};
return r;
}
When passed to a function, a struct is copied in full, just like an int.
Task. Describe a struct rect with the fields width and height, and write a function int area(struct rect r). The program reads the width and height and prints the area.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.