In continuation of my previous blog on c pointers, we’ll dig little deeper into pointers ☺️ .
1. Array of pointers
As the name suggests, we can have an array of pointers, as shown below.
for ( int idx=0; idx < 10; idx ++ )
PtrNumbers[idx] = &numbers[idx];
Here, each member of ptrNumbers array stores the address of different members of numbers array.
Here, names is an array of pointers, each pointer storing the starting address of each name.
names = “pooja“;
names=”grover”; and so on…
If we don’t know the size of string before, we can allocate exact size memory dynamically as shown below.
char *userName = (char *)malloc(sizeof(char)*(LEN+1));
strcpy (username, “pooja”);
2. Passing pointer as function parameter
Also called, passed by reference, when the address of a variable is passed as a function parameter, the value of that variable can be modified within that function.
myFunRef( int *addPassedVar)
*addPassedVar = 100;
Here, the value at the address pointed to by addPassedVar is modified and changed to 100 inside this function.
3. Function pointers
Function pointers store the address of the code of the function, and not of any data.
Function pointer is declared and initialized as:
int (*ptrMyfunction)(int) = &myFunction;
The function can then be invoked using pointers as:
An array of function pointers is used for storing addresses of multiple functions.
This is mainly used inplace of switch statement.
Array of function pointers is declared as below:
Then, depending on the value of index, the appropriate function gets invoked.
Friends, we have covered some important uses of pointers here. In my next blog (brushing up C part 5 ), I will be taking up linked lists, stack, queue etc using pointers.
Happy coding ☺️ .
Here is my blog on python, python simplified .