struct
is just another word for "record"
A data table can be stored as an array of structs.
Shopping List | ||
---|---|---|
Apples | 2 | kg |
Lemonade | 4 | l |
Bread | 1 | kg |
Example: Calculate the centroid of a triangle.
def centroid(x_A, y_A, x_B, y_B, x_C, y_C):
x_G = 1 / 3 * (x_A + x_B + x_C)
y_G = 1 / 3 * (y_A + y_B + y_C)
return x_G, y_G
Without structs, returning more than one value is not possible in C.
struct struct_name {
type member1;
type member2;
/* declare as many members as desired */
};
struct date {
int year;
int month;
int day;
};
struct date d = { 2021, 12, 10 };
struct date d = { .year=2021, .month=12, .day=10 };
typedef type_definition new_identifier;
struct point {
float x;
float y;
};
struct point p = {1.5, 3.0};
typedef
improves the readability.
typedef struct point {
float x;
float y;
} Point;
Point p = {1.5, 3.0};
#include <stdio.h>
typedef struct {
float x;
float y;
} Point;
int main() {
Point p1 = { .x=1.5 , .y=3.0 };
Point p2 = p1; // copy assignment
p2.x = -5; // does not affect `p1`
return 0;
}
#include <stdio.h>
typedef struct {
float x;
float y;
} Point;
void print_point(Point p) {
printf("P(%.2f/%.2f)\n", p.x, p.y);
p.x = 0; // does not affect p in main
}
int main() {
Point p = { .x=1.5 , .y=3.0 };
print_point(p); // pass by value
return 0;
}
typedef struct {
float x;
float y;
} Point;
Point centroid(Point A, Point B, Point C) {
float x_G = 1.0 / 3.0 * (A.x + B.x + C.x);
float y_G = 1.0 / 3.0 * (A.y + B.y + C.y);
Point G = {x_G, y_G};
return G;
}
int main() {
Point A = {1.5, 3.0}, B = {12.0, 3.0}, C = {4.5, 9.0};
Point G = centroid(A, B, C); // pass by value
return 0;
}
#include <stdio.h>
typedef struct {
int id;
char name[15];
unsigned int grades[8];
} Student;
Student read_student(int id) {
// get data from eg. a database
Student s = { id, "Pat Kaling", { 1, 1, 2, 1, 3, 2, 1, 1 } }; // from a database
return s;
}
int main() {
Student s = read_student(123);
printf("%s has a %u in English.", s.name, s.grades[3]);
return 0;
}
typedef struct Date
that holds
int year
,
int month
and int day
.print_date(Date d)
that uses
printf
to print a given date to standard output. The date
must be printed in
ISO 8601
format (YYYY-MM-DD), followed by a newline.Date
in main
and call
print_date
to print today's date.#include <stdio.h>
typedef struct {
int year;
int month;
int day;
} Date;
void print_date(Date d) {
printf("%04d-%02d-%02d\n", d.year, d.month, d.day);
}
int main() {
Date today = {2021, 12, 9};
print_date(today);
return 0;
}