1/8
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
Variable Issues
can only represent ‘simple’ scalar values, or as fixed length arrays of values
they are declared with a fixed size
go ‘out of scope’ at the end of the block they are declared in
they incur overhead when copied (e.g. when passed into a function)
we can can overcome these issues using compound variables, ‘dynamic’ memory, and passing pointers
Different Types of Storage
literals are compiled into our program
standard ‘variables’ are managed automatically by the compiler (on the stack) - they go in/out of scope
global variables
dynamic variables allocated from ‘the heap’
the heap is dynamic memory
Dynamic Memory
allocated at runtime by your code/the programmer
needs managing (e.g. free and return to the heap when you’re done)
extreme care required to avoid memory problems, memory leaks, crashing programs
malloc()
get a pointer to some memory
//create pointer str to 100 bytes
char *str = (char *) malloc(sizeof(char) * 100);
//do something with it
str[0] = 'h';
strcpy(str, "hello");
//return str to the heap
free(str);
sizeof(char) - how big is char
* 100 - multiply by size we want
malloc(100) - allocate the heap space (return a pointer)
char *str - declare the pointer ‘str’
= (char *) - ‘cast’ the pointer to be of the type ‘points to char’
Compound Types
combine single types into an ‘entity’
The ‘struct’
a user defining group of variables (possibly even other nested structs)
/*declare a new type (not variable, struct person)*/
struct person {
char name[20];
int age;
char gender; //single letter e.g. f
};
//declare the variable of type struct person
struct person aPerson;
Accessing a struct
. notation
struct person aPerson;
strcpy(aPerson.name, "Nigel");
aPerson.age = 30;
aPerson.gender = 'm';
Array of structs
struct person *people; /*pointer to a 'type struct person'*/
//allocating some memory
if ((people = (struct person *)
malloc(sizeof(struct person) * 100))
!= NULL) {
//it worked, do something with 100 people
//free when done
people[50].age = 18; /*age field in 50th person in people array*/
free(people);
}
else {
//oh no, out of memory
}
Access a struct field from a Pointer
struct person *p = &aPerson;
strcpy(p->name, "Nigel");
p->age = 30;
p->gender = 'm';
printf("%s's age is %d\n", p->name, p->age);