C Programming 2
Compound data type: union Consider the following code: #include <stdio.h> #include <string.h> union id { int student; char faculty[256]; }; union id personnel; void main() { strcpy(personnel.faculty, "A1120989"); personnel.student = 1000798123; printf("The student id is %d\n", personnel.student); printf("The faculty id is %s\n", personnel.faculty); printf("The size of id is %d", sizeof(personnel)); } What is the "sizeof" the union personnel?
256
Compound data type: struct Consider the following code: #include <stdio.h> #include <string.h> struct Course { int sln; char title[256]; char instructor[250]; int time; }; struct Course ser222; void main() { ser222.sln = 1774; strcpy(ser222.title, "Data Structures & Algorithms"); strcpy(ser222.instructor, "Acuna, Ruben"); printf("Memory allocated for this structure is %d", sizeof(ser222)); } How much memory is allocated for this structure?
516 bytes
Declaring Enumerations Consider the following code: enum { Sun=0, Mon, Tue, Wed, Thu, Fri, Sat } days; enum days day = Mon; What does the "sun=0" part do?
Forces enum elements to be numbered from zero - otherwise their values are not well defined.
Using Enumerations Consider the following code? Days x = Mon, y = Fri; while (x != y) x++; What is the value of x, after x++ is executed and if x was Sat before?
If x was saturday, then x = 6. If you do x++ then the value becomes a 7. 7 isn't actually mapped to any of the days of the week. That is a potential problem. We want to avoid doing manipulation like ++ and hard code what the value should be.
Compound data type: struct Consider the following code: #include <stdio.h> #include <string.h> struct Course { int sln; char title[256]; char instructor[250]; int time; }; struct Course ser222; void main() { ser222.sln = 1774; strcpy(ser222.title, "Data Structures & Algorithms"); strcpy(ser222.instructor, "Acuna, Ruben"); printf("Memory allocated for this structure is %d", sizeof(ser222)); } What does "sizeof(ser222)" do?
It goes to a particular data type to find how many bytes it takes up. In this case, it finds how many bytes are needed for the ser222 course.
Compound data type: struct Why is structure useful?
It's useful when you have pieces of data that need to go together. Let's say I have points like x and y or a rectangle with points and height and width: that's where I want to have a struct because I want to keep those pieces of information together.
Parameter Passing Different languages have different ways of implementing parameter passing. C has two general mechanisms:
Pass-by-value Pass-by-address (pointer)
Compound data type: union Why is union useful?
Sometimes you don' t know ahead of time what we want to store in a variable.
Implementing Nodes Write an example of a Node
Struct Node{ char name [length]; int data; char email[length] struct Node* next; };
Compound data type: struct Consider the following code: #include <stdio.h> #include <string.h> struct Course { int sln; char title[256]; char instructor[250]; int time; }; struct Course ser222; void main() { ser222.sln = 1774; strcpy(ser222.title, "Data Structures & Algorithms"); strcpy(ser222.instructor, "Acuna, Ruben"); printf("Memory allocated for this structure is %d", sizeof(ser222)); } The memory should be 514 instead of 516? Why are there 2 more bytes?
The char array called instructor is 250 bytes. 250 is not a multiple of 4. A 32 bit processor can read 4 bytes at a time. A 64 bit processor can read 8 bytes at a time. The processor adds padding of 2 bytes to align the data in memory.
Creating types with typedef Why not just use the variable type directly?
The reason is annotation. You know more about what the variable is. For example typedef char FlagType is not just a char, it is a flag. It is just another way to use semantics to let us know how the variable is supposed to be used.
Compound data type: union How is memory allocated for a union?
The size of a struct instead of being the sum of the size of each of the elements inside of it.....it is simply the size of the largest thing inside of it because it needs to have space to store that thing. If the union is using an element that is smaller than the largest thing, then it will only use the amount of bytes needed for that smaller element. The different elements in the union are stacked on top of each other instead of listed in a straight line. The largest element is at the bottom.
Structure Padding Why is it important to align the data correctly to avoid unnecessary paddings?
Unnecessary padding takes up time and memory.
Pass by Reference
Value being passed in copied to a new location
Pass by value
Value being passed in copied to a new location
Pass by reference (pointer)
Value being passed in copied to a whole new location
Implementing Nodes How can we represent an empty list?
We can use "NULL".
Implementing Nodes How do you retrieve a node from a linked list?
We will retrieve the node before the node we want so we can have more flexibility. struct Node* selectByName(char* name, struct Node* front){ struct Node* prev = NULL; struct Node* iter = front; while(iter != NULL){ if(strcmp(iter->name, name) == 0) return prev; else{ prev = iter; iter = iter->next; } } return NULL; } int main(){ .... struct Node* sel = selectByName("name", list); free(sel->next); sel->next = NULL; }
Compound data type: union Consider the following code: #include <stdio.h> #include <string.h> union id { int student; char faculty[256]; }; union id personnel; void main() { strcpy(personnel.faculty, "A1120989"); personnel.student = 1000798123; printf("The student id is %d\n", personnel.student); printf("The faculty id is %s\n", personnel.faculty); printf("The size of id is %d", sizeof(personnel)); } Why is the output show "The faculty id is 1/2^a;0989"?
You don't get the string that is stored in faculty because the first part of the string..... the first four bytes have been overwritten by the bytes that are needed to store the student id number.
Implementing Nodes What is a node?
a collection of two sub-elements or parts. A data part that stores the element and a next part that stores the link to the next node.
Parameter Passing Pass-by-value
a formal parameter is a local variable in the function. It is initialized to the value of the actual parameter. It is a copy of the actual parameter. The copy will exist as an entry in a new function stack frame.
Functions and parameter passing The purpose of functions are twofold:
abstraction and reusability
Pointers consider the following code: int var; var = 10; int *ptr = &var; *ptr = 20; int **ptrPtr = &ptr; **ptrPtr = 30; What is stored in memory for ptrPtr?
address of ptr
Using Enumerations Recall in that the previous example we created a variable with "enum days day;". This is a little awkward because we have to write "enum days" for the type name. How can we fix this with typdef?
enum { Sun=0, Mon, Tue, Wed, Thu, Fri, Sat } days; typedef enum days Days; Days now = Mon;
Implementing Nodes What is a list?
formed when multiple nodes are linked together to form a chain.
Pointers main.c struct grade_node { int value; char assignment[255]; struct grade_node *next;}; } // lets create the first element
head = malloc(sizeof(struct grade_node));
Declaring Enumerations Another keyword is enum, which allows us to ________
define a type that is to be populated by specific elements (symbols).
Pointers Each '*' is one level of _________
dereferencing
When to use pointer to pointer - 2D arrays When size of array _______
determined (rows and columns)
When to use pointer to pointer - 2D arrays When you want to ______ allocation of a 2D array of any type.
dynamic memory
When to use pointer to pointer - 2D arrays If you want value of a pointer - must have _________
one level of dereferencing
When to use pointer to pointer - 2D arrays each [ ] or * is _________
one level of dereferencing the pointer
Compound data type: union At any moment, a union can contain _________
only one value.
When to use pointer to pointer - 2D arrays Declare as _________
pointer, say name **ptr
When to use pointer to pointer - 2D arrays Access each element now as ________
ptr[vectID][index] or *(ptr[vectID] + index)
Compound data type: union A union is a ________
region of shared memory that, over time, can contain values with different data types.
Implementing Nodes How do you remove a node from the front of a linked list?
removeFront(struct Node* front){ if(front != NULL) struct Node* temp = front; front = front->next; free(temp); }
Accessing members of a struct Consider the following code: struct Course { int sln; char title[256]; char instructor[250]; int time; } struct Course ser222; struct Course* cse360; Write an example of direct access to the data (stack memory)
ser222.sln = 1774; strcpy(ser222.title, "Data Structures & Algorithms"); strcpy(ser222.instructor, "Acuna, Ruben");
Functions and parameter passing Reusability
statements that can be executed in more than one place in the program.
Functions and parameter passing Abstraction
statements that form a conceptual unit.
Implementing Nodes How do you add a node to the front of an existing linked list?
struct Node* addfront(struct Node* node, struct Node* front){ node->next = front; front = node; return front; }
Pointers main.c struct grade_node { int value; char assignment[255]; struct grade_node *next;}; } void create_head1(struct grade_node *head);struct grade_node *create_head2(struct grade_node *head);void create_head3(struct grade_node **head); // start by defining an allocating a linked list for grade_node; // it is NULL as it does not have any members in the list yet
struct grade_node *head = NULL, *head2 = NULL, *head3 = NULL; struct grade_node *headCreateInFunction = NULL;
Parameter Passing Pass-by-address (pointer)
the formal parameter is a pointer to the actual parameter. The address will be stored as entry in the stack frame, but may point to both stack or heap memory. (This is technically known as pass-by-reference implemented by using pointers with pass-by-value.)
Pass by reference (pointer) Pass by reference =
the location of non-primitive is known and can be directly access and modified by called method()
Compound data type: union Programmers must make sure ___________
the proper type is used at the proper time.
Using Enumerations Consider the following code? Days x = Mon, y = Fri; while (x != y) x++; What is the final value of x?
thurs
Declaring Enumerations Note that an enum value is not ______.
type safe
Compound data type: struct What can you do if you don't like having to put struct in front of the typename?
use typedef
Pointers consider the following code: int var; var = 10; int *ptr = &var; *ptr = 20; int **ptrPtr = &ptr; **ptrPtr = 30; In this code snippet: each code segments modify ________
var
Functions and parameter passing When calling a function, actual parameters (also known as arguments) are given. Actual parameters are ________
variables/values of the caller.
Pointers A non-ptr variable can have _______ size
vary
Implementing Nodes How do you traverse a linked list and display all the contents?
void display(struct Node* front){ struct Node* iter = front; while(front){ printf("name: %s\n", iter->name); iter = iter->next; } }
Implementing Nodes As a first step to creating a list, __________
we need to implement a node struct.
Pass by value = parameters passed in ______ be modified in the calling function
will NOT (only the copy gets modified)!
Functions and parameter passing Functions communicate with the rest of the program by:
▪ Either changing the global/static variables ▪ Using parameters and/or return values
When to use pointer to pointer - 2D arrays If you want value of a pointer to pointer - then need ________
2 levels of dereferencing
Consider the following snippet of code. struct point_2d { int x ; int y ; Color col ; } ; void main ( ) { point_2d∗ data [ 5 ] ; for ( int i = 0 ; i < 5 ; i++) { point_2d tmp ; tmp . x = i ; tmp . y = i ∗ i ; data [ i ] = &tmp ; } for ( int i = 0 ; i < 5 ; i++) printf ( " Point ␣#%d : ␣%d , ␣%d" , i , data [i]−>x , data [i]−>y) ; } What will be the output?
"Point #0: 4, 16", "Point #1: 4, 16", "Point #2: 4, 16", "Point #3: 4, 16", and "Point #4: 4, 16".
Accessing members of a struct Consider the following code: struct Course { int sln; char title[256]; char instructor[250]; int time; } struct Course ser222; struct Course* cse360; Write an example of Indirect access (using pointer) to the data (heap memory)
(*cse360).sln = 2234; //same as arrow notation below strcpy(cse360->title, "Introduction to SW Engineering"); strcpy(cse360->instructor, "Tsai, Wei-Tek");
Pass by reference Consider the following code: int val1 = -55, val2 = 12; foobar(&val1, &val2); ... foobar(int *in1, int *in2) { ... *in1 = ....; *in2 = ....; ... } What is stored in memory for val1?
-55
Pass by value Consider the following code: int val1 = -55, val2 = 12; foobar(val1, val2); ... foobar(in1, in2) { ... in1 = ....; in2 = ....; ... } What is stored in memory for val1?
-55
Pass by value Consider the following code: int val1 = -55, val2 = 12; foobar(val1, val2); ... foobar(in1, in2) { ... in1 = ....; in2 = ....; ... } What is stored in memory for in1?
-55 → changed in foobar
Declaring Enumerations Write an example of boolean enum
// doesn't name the enum type so later can't be referenced; but declares a var of that type enum { false , true } x; void main() { x = false; int counter = 5; if (x == true ) counter++; }
Structure Padding a computer processor can read __________
1 word from memory at a time. (In a 32-bit processor it is 4 bytes and 8-bytes for a 64-bit processor.)
Pointers consider the following code: int var; var = 10; int *ptr = &var; *ptr = 20; int **ptrPtr = &ptr; **ptrPtr = 30; What is stored in memory for var?
10 → 20 → 30
Pointers to structs consider the following code: struct gradeNode { int value; char assignment[255]; struct grade_node *next }; ... struct gradeNode node, *ptrNode = &node, **ptrPtrNode = &ptrNode; Node.value = 10; (*ptrNode).value = 20; // or ptrNode->x = 20; (**ptrPtrNode).value = 30; // or (*ptrPtrNode)->value = 30; what is the value stored in memory for node?
10 → 20 → 30
Pass by reference Consider the following code: int val1 = -55, val2 = 12; foobar(&val1, &val2); ... foobar(int *in1, int *in2) { ... *in1 = ....; *in2 = ....; ... } What is stored in memory for val2?
12
Pass by value Consider the following code: int val1 = -55, val2 = 12; foobar(val1, val2); ... foobar(in1, in2) { ... in1 = ....; in2 = ....; ... } What is stored in memory for val2?
12
Pass by value Consider the following code: int val1 = -55, val2 = 12; foobar(val1, val2); ... foobar(in1, in2) { ... in1 = ....; in2 = ....; ... } What is stored in memory for in2?
12 → changed in foobar
Compound data type: struct What is created by the keyword struct?
A structure
Compound data type: union What is the difference between a struct and a union?
A union contains only one value at a time. A struct can contain many values at a time.
Pointers to structs consider the following code: struct gradeNode { int value; char assignment[255]; struct grade_node *next }; ... struct gradeNode node, *ptrNode = &node, **ptrPtrNode = &ptrNode; Node.value = 10; (*ptrNode).value = 20; // or ptrNode->x = 20; (**ptrPtrNode).value = 30; // or (*ptrPtrNode)->value = 30; What is stored in memory for ptrPtrNode?
address of ptrNode
Pass by reference Consider the following code: int val1 = -55, val2 = 12; foobar(&val1, &val2); ... foobar(int *in1, int *in2) { ... *in1 = ....; *in2 = ....; ... } What is stored in memory for in1?
address of val1
Pass by reference Consider the following code: int val1 = -55, val2 = 12; foobar(&val1, &val2); ... foobar(int *in1, int *in2) { ... *in1 = ....; *in2 = ....; ... } What is stored in memory for in2?
address of val2
Pointers consider the following code: int var; var = 10; int *ptr = &var; *ptr = 20; int **ptrPtr = &ptr; **ptrPtr = 30; What is stored in memory for ptr?
address of var
Pointers to structs consider the following code: struct gradeNode { int value; char assignment[255]; struct grade_node *next }; ... struct gradeNode node, *ptrNode = &node, **ptrPtrNode = &ptrNode; Node.value = 10; (*ptrNode).value = 20; // or ptrNode->x = 20; (**ptrPtrNode).value = 30; // or (*ptrPtrNode)->value = 30; What is stored in memory for prtNode?
address to node
Structure Padding Padding is needed to ________
align the data in memory
When to use pointer to pointer - 2D arrays for each vector pointer i.e. ptr[index] or *(ptr+index), _________
allocate enough space for each vector
Declaring Enumerations In C, each enum value is _________
an actual int, and can be directly manipulated.
Pointers A double pointer is ______ too
an address
Pointers A pointer to any variable is ________
an address
Compound data type: struct A structure is __________
composite data type, similar to a class in Java but only containing state.
Implementing Nodes How can we link nodes together?
create a reference to a new variable that's a pointer type to the same type of node struct. struct ContactNode* next; We have to use pointers. "A" will have a variable inside of it called next which is effectively a pointer to another node
Accessing members of a struct Consider the following code: struct Course { int sln; char title[256]; char instructor[250]; int time; } struct Course ser222; struct Course* cse360; Write an example of Dynamic Allocation in heap memory
cse360 = (struct Course*)malloc(sizeof(struct Course));
Pointers consider the following code: int var; var = 10; int *ptr = &var; *ptr = 20; int **ptrPtr = &ptr; **ptrPtr = 30; What is the size of each variable for 32 bit machine?
in this case var, ptr, and ptrPtr are all sized 4 bytes for a 32 bit machine ie. sizeof(int) = sizeof(int *) = sizeof(int **);
Implementing Nodes How do you deallocate a linked list once you're done with it?
int main(){ .... while(list != null){ list = removeFront(list); } }
Creating types with typedef The typedef keyword
introduces a new name that becomes a synonym for the type given by the typename portion of the declaration.
Parameter Passing What is a disadvantage of Pass-by-value?
less flexible/less powerful.
Functions and parameter passing In the declaration of a function, formal parameters are given, which are _________
local variables of the function.
Pass by reference = you can modify ________
location / address
Pointers Address size dependent on _________
machine e.g. 32 bit machine - address will be size of 4 bytes
Functions and parameter passing A function/method/procedure/subroutine is a __________
named block of code that must be explicitly called.
Parameter Passing What is an advantage of Pass-by-value?
no side-effects (safe and reliable).