Ladder
Structs
Structs organize and group variables in a container so that they're easily accessible by a single pointer.
As in other languages, creating objects is extremely helpful in keeping your abstractions clean!
Let's analyze the code
We can declare a struct type by using the
struct name {fields}
syntax.To access fields of a struct value, we can use the
.
syntax.To access fields of a struct pointer, we have two choices
We can dereference the pointer to get a struct value and then use the
.
notationOr we can use the arrow notation
->
to quickly do the first optionThe arrow notation is probably the cleaner and quicker method
When we pass struct values into functions (such as
modify1
), they are copiedThis means any changes we make to that struct are not reflected in the original struct
When we pass struct pointers into functions (such as
modify2
), the original struct may be modifiedSince we have a pointer, we can go to the location of the struct and modify that struct
#include <stdio.h>
// Declare a struct type
struct coord {
int x;
int y;
};
int main(int argc, char *argv[]) {
// Declare a struct on the stack
struct coord c1;
// We can access and assign fields using the . syntax
c1.x = 3;
c1.y = 4;
// Declare a struct on the heap
struct coord *c2 = malloc(sizeof(struct coord));
// This dereferences the struct pointer to get the struct
// and accesses its field x
(*c2).x = 3;
// When we have a pointer to a struct we can use
// the arrow syntax to quickly reference its fields
c2->y = 4;
// No change because a copy of the struct is passed
modify1(c1);
modify1(*c2);
printf("modify1\n");
printf("x: %d, y: %d\n", c1.x, c1.y);
printf("x: %d, y: %d\n", c2->x, c2->y);
// Change because we passed a pointer to the struct
modify2(&c1);
modify2(c2);
printf("modify2\n");
printf("x: %d, y: %d\n", c1.x, c1.y);
printf("x: %d, y: %d\n", c2->x, c2->y);
return 0;
}
// structs are copied if given the struct itself
void modify1(struct coord c) {
c.x = 5;
c.y = 6;
}
void modify2(struct coord *c) {
c->x = 5;
c->y = 6;
}
Output:
modify1
x: 3, y:4
x: 3, y:4
modify2
x: 5, y:6
x: 5, y:6