1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
|
[\<- Notes 01/13](01-13.md)
---
Notes 01/15/2020
# Review Pointers
Below is an example to demonstrate pointer precedence:
```
int x[] = {0, 5, 10, 15, 20, 25, ...};
int y = 5;
int *p = x;
y = ++*p
printf("%d, %d\n", y, *p);
y = *(++p);
printf(...); //ditto
y = ++(*p);
printf(...); //ditto
```
The code outputs the following:
```
1, 1
5, 5
6, 6
```
---
# Introduction to Structures in C
- Earlier we talked about data types: int, char
- A Structure allows for multiple data types in one array
- Structure Basics
- A structure is a collection of values, called members
- Outline of Structure Definition:
```
struct name{
variable declaration;
variable declaration;
...
};
```
- The keyword struct signifies that this is a structure definition
- Example:
```
struct info{
int number;
char character;
char string[10];
int array[10];
};
```
- As can be seen in the example, multiple different data types are included as members of `info`
- This example **does not allocate any memory**
- Instead, it simply tells C that now there is a new kind of data type called `struct info`
- Let's create a sample `struct info`:
```
struct info real_info;
struct info *p;
```
- Memory **is** allocated for real\_info
- Member variables of a struct can be accessed using `.`
- For example:
```
p = &real_info //*p will point to real_info now
real_info.number = 2;
real_info.character = 'A';
```
- Let's see a visual representation of real\_info in memory
| real_info.number | real_info.character | real_info.string[] | real_info.array[] |
| - | - | - | - |
| 2 | 'A' | ... | ... |
- `real_info.string[]` and `real_info.array[]` show `...` because to show the full visual representation in memory, I would have to show `real_info.string[0]`, `real_info.string[1]`, etc.
- To access structure members with a pointer (such as `*p` defined above), use `->`
- For example:
```
p->number = 2;
p->character = 'B';
p->array[0] = 3;
```
- The above code changes three members of real\_info in memory to the following:
| real_info.number | real_info.character | real_info.string[] | real_info.array[0] |
| - | - | - | - |
| 2 | 'B' | ... | 3 |
---
- Another Example:
```
struct node{
int number;
struct node *link;
};
```
- We will talk more about links later
---
[-> Notes 01/17](01-17.md)
|