summaryrefslogtreecommitdiff
path: root/01-17.md
blob: 48a3b00df528f4749077b7cb284a4629018352f1 (plain)
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
123
124
125
126
127
128
[\<- Notes 01/15](01-15.md)

---

# Structures Continued

- typedef can be used to give the structure an alias
	- For example:

```
typedef struct info{
	int number;
	char character;
	char string[10];
	int array[10];
} INFO;

...

INFO real_info;
INFO *p;
```

- In the above example, struct info is called "INFO"
- The same can be done using a `#define` statement:

```
#define INFO struct info

...

struct info{
	int number;
	char character;
	char string[10];
	int array[10];
};

...

INFO real_info;
INFO *p;
```

- Initializing a struct in one line:

```
struct info{
	int number;
	char character;
	char string[10];
	int array[10];
};

struct info i1 = {99, 'Z', "abc", {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}};
```

- Alternatively, you can set members one at a time:

```
struct info1, info2;
...
info1.number = 99;
info1.character = 'Z';
strcpy(info1.string, "abc");
for(i = 0; i < 10; i++){
	info1.array[i] = i;
}
```

- You can also copy one structure to another very easily:

```
info2 = info1;
```

- Now I want to print each member of `i1`:

```
printf("%d\n", i1.number);
printf("%c\n", i1.character);
printf("%s\n", i1.string);
for(i = 0; i < 10; i++){
	printf("%d\n", i1.array[i]);
}
```

- Arrays of structures can also be declared:

```
struct info lots_of_info[20];
lots_of_info[0].number = 17;
```

- Here is a struct in action:

```
struct simple{
	int value1;
	int value2;
}

int main(void){
	struct simple s1 = {10, 15};
	...
}
```

- Structures can be passed as an argument either as a "Call by Value" or "Call by Reference
- Example of "Call by Value":

```
void fun1(struct simple s){
	s.value1++;
	s.value2*=2;
}
```

- Example of "Call by Reference":

```
void fun1(struct simple *s){
	s->value1++;
	s->value2*=2;
}
```

- This is the same idea as passing variables as copies versus as pointers to memory