From 882ae24f13b65c8401d7ef943914ba2c29dde99a Mon Sep 17 00:00:00 2001 From: loshprung Date: Wed, 15 Jan 2020 17:34:38 -0800 Subject: Added additional info about structures to 01-15.md --- 01-15.md | 53 ++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 44 insertions(+), 9 deletions(-) (limited to '01-15.md') diff --git a/01-15.md b/01-15.md index bf362d1..a23c3b5 100644 --- a/01-15.md +++ b/01-15.md @@ -32,7 +32,7 @@ The code outputs the following: # Introduction to Structures in C --`Earlier we talked about data types: int, char +- 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 @@ -47,6 +47,8 @@ struct name{ }; ``` +- The keyword struct signifies that this is a structure definition + - Example: ``` @@ -58,17 +60,49 @@ struct info{ }; ``` -- Let's see the memory: +- 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: -| | | -| - | - | -| | | -| Real_Info | 55 bytes of storage | -| | | +``` +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; +0->character = 'B'; +p->array[0] = 3; +``` -- You can also create pointers to data structures +- The above code changes three members of real\_info in memory to the following: -- Defines a structure type +| real_info.number | real_info.character | real_info.string[] | real_info.array[0] | +| - | - | - | - | +| 2 | 'B' | ... | 3 | --- @@ -81,3 +115,4 @@ struct node{ }; ``` +- We will talk more about links later -- cgit