As promised in my last blog on C, we’ll be taking up pointers now.
Ask any programmer, and the first emotion that she feels on hearing pointers is fear ☺️ . But they do so much of work, it’s just impossible to ignore them ☺️ .
1. So, what are pointers?
Just like we all have an address where we live, every piece of information in software has an address where it is stored in memory.
Address is pointer.
A variable that holds address is called pointer.
- A pointer holding the address of an Integer type variable is called an integer pointer.
- Similarly, there are char and float pointers.
2. How are they represented?
addofA = &varA;
varA = 10;
‘&’ means address. ‘&varA’ means address of varA.
‘addofA = &varA’ assigns the address of varA to addofA, where addofA is declared as a pointer. Pretty obvious ☺️ . Note both variables are of int type.
addofB = &varB;
3. Accessing data with pointers
Once you have created a pointer and assigned an address to it, you can easily access the value stored at that address using the pointer.
printf (” value of varA is %d \n”, *addofA);
Output will be:
value of varA is 10
Value stored at the address pointed to by pointer is obtained by prefixing ‘*’ before the pointer variable like
newVar = *addofA;
4. malloc and free
malloc and free are used to dynamically allocate memory, and release that memory when no longer needed.
int * ptrZ =(int *)malloc (100 * sizeof(int));
Here, memory to store 100 integers is created. ptrZ is assigned the address of first allocated location.
Rest of the locations here are accessed as
(ptrZ +1),( ptrZ + 2)….
Values can be assigned as
*(ptrZ + 1) = 7;
Simple, or not ☺️ .
We can then free up this memory when not needed, using free .
free ( ptrZ) ;
Friends, I hope this tutorial helped you in getting familiar with pointers. Please let me know if you would like to know anything more ☺️ .
I would be taking up some interesting implementation of pointers in my next blog of this series, do keep reading ☺️ .
Here is my next blog on interesting implementation of pointers .