From 272aeb46a56e3875e639c1f263f5134ea028af06 Mon Sep 17 00:00:00 2001 From: loshprung Date: Fri, 17 Jan 2020 11:34:43 -0800 Subject: Post-class 01/17 --- 01-15.md | 4 ++ 01-17.md | 128 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 132 insertions(+) create mode 100644 01-17.md diff --git a/01-15.md b/01-15.md index 31e93f9..106b1bf 100644 --- a/01-15.md +++ b/01-15.md @@ -116,3 +116,7 @@ struct node{ ``` - We will talk more about links later + +--- + +[-> Notes 01/17](01-17.md) diff --git a/01-17.md b/01-17.md new file mode 100644 index 0000000..48a3b00 --- /dev/null +++ b/01-17.md @@ -0,0 +1,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 -- cgit