Week 3 - Pointers and Memory Addressing Flashcards
Name the 5 base data types in C.
Char, int, float, double, pointer
How would you declare a pointer p to a character in C?
char p;
or
char p;
How would you assign p to the address of/as a pointer to ch in C?
p = &ch;
char ch = ‘A’;
char *p;
p = &ch;
What does p contain?
The address of where ch is stored in memory
If x is any datatype, then what is &x in C?
The location in memory (its “address”) where x is currently stored
If x is a pointer in C, then what does <datatype> *x; declare?</datatype>
Declares x to contain the memory address of a variable of type <datatype></datatype>
*x says: go to the memory address stored in x and bring back the value (of type <datatype> stored there</datatype>
What is “dereferencing the pointer” in C?
*x, which says: go to the memory address stored in x and bring back the value (of type <datatype> stored there</datatype>
How do you calculate the amount of memory used to store a pointer?
sizeof(), normally dependant on the OS
What can void pointers do in C?
Point to any datatype, but need to be cast when used
What are the two runtime errors when using pointers in C, and how are they caused?
Memory fault & segmentation fault
Caused by trying to access memory which it is not allowed to access, and trying to access memory in a way that is not allowed, e.g. trying to overwrite the operating system
Sometimes in C, you don’t know at compile time how much memory you will need at runtime. What are the 3 possible solutions?
- Declare an array whose size is decided at runtime (but no way of knowing how much free contiguous memory is available or how much is required before declaring the array)
- Process the data in smaller chunks (possible with lots of extra programming)
- Dynamically allocate memory at runtime using pointers (so can check whether memory allocation was successful)
What C header file is needed to include NULL and malloc?
stdlib.h
When using malloc in C, what must you always trap?
The fact that memory was not allocated
When using malloc in C, when must you always free the memory?
Before the variable goes out of scope
How do you free memory stored in pointer p in C?
free(p);