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.
*)eg. int *ptr;int a = 2; ptr = &a;
int value = *ptr;
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 a = 67; void *ptr; // void pointer ptr = &a; // assign address of an int to void* int y = *(int *)ptr; // cast void* to int* before dereferencing
Describe how function pointers can be used in ‘C’.In what ways do function pointers differ from other pointers? Illustrate your answer with code snippets.
Function pointers allow functions to be passed as arguments to other functions, enabling generic functions whose behaviour depends on the function supplied.
Structure:
return type (*pointer_name) (parameters)
int add(int a, int b){
return a + b;
}
int main(){
int (*ptr_add)(int,int)
ptr_add = add;
int result = (*ptr_add)(5,4);
return 0;
}In what situations would function pointers be useful (and why)?
Callbacks: Passing a functions address to another function so it can be excecuted 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 statment.
What are the advantages of using function pointers
in ‘C’. Illustrate your answer with code snippets.
Advantages:
1. Flexibility: Allows the same code to work with different functions
int apply(int (*funct)(int,int), int a, int b){
return funct(a,b);
}void onEvent(void (*handler)()){
handler();
}What are the disadvantages of using function pointers
in ‘C’. Illustrate your answer with code snippets.
int (*fp)(int,int);