How are pointers (not function pointers) used in C?
Pointers in C are primarily used to store the memory address of another variable. They allow for indirect access and manipulation of data.
Key uses: Dynamic memory allocation, Array manipulation
What are the steps involved in using pointers? Illustrate your answer with code snippets.
How is dynamic memory allocation handled in ‘C’? In your own words
During runtime
- The memory is allocated from the heap
- Allows a program to manage a variable amount of memory rather than relying on fixed memory allocated at compile time.
The standard C library provides 4 primary functions to manage memory dynamically:
malloc: Allocates a block of uninitialized memory of a specified size and returns a void * pointer to the start of the block
calloc: Allocates an array in memory for a specified number of elements with all bits initialized to 0, also returns a void * pointer
realloc: Changes the size of a previously allocated block of memory, takes the old pointer and the new size.
free: Releases the dynamically allocated memory back to the system’s heap. Crucial for preventing memory leaks
What can the type void* be used for? Give a simple example, including
assigning a value to a variable of type void*.
void * is used as a generic pointer that can hold the memory address of any data type.
int main(){
int num = 32;
void *genPointer = #
printf(“The void pointer must be cast to the correct type: %d”, * (int *)genPointer);
}
Describe how function pointers can be used in ‘C’.
Variable that stores the address of an executable function.
return_type (*pointer_name)(parameter_list);
int add(int a, int b){
return a + b;
}
int main(){
int (*ptr_add)(int, int);
ptr_add = add; int result = (*ptr_add)(5,3);
In what ways do function pointers differ
from other pointers? Illustrate your answer with code snippets.
In what situations would function pointers be useful (and why)?
Callbacks
Passing a functions address to another function so it can be executed upon an event like a button click
Generic algorithms
Allowing a standard function (like qsort) to perform a custom action (like comparison logic) supplied via the pointer
Jump tables
Storing pointers in an array to quickly execute a chosen function based on an index, rather than a large switch statement