Brushing up C part 4 more pointers

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.

int numbers[10];

int *ptrNumbers[10];

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.

char names[][]={“pooja”,”grover”,”sheena”,”jane”};

Here, names is an array of pointers, each pointer storing the starting address of each name.

names[0] = “pooja“;

names[1]=”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.

int myFunction(int)

{

//Function code

}

Function pointer is declared and initialized as:

int (*ptrMyfunction)(int) = &myFunction;

The function can then be invoked using pointers as:

(*ptrMyfunction)(5);

or

ptrMyfunction(5);

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:

void (*arrayfuncptr[])(int)={func1,func2,func3};

Then, depending on the value of index, the appropriate function gets invoked.

(*arrayfuncptr[index])(value);


Summary

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 .

Advertisements

2 thoughts on “Brushing up C part 4 more pointers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s