Why do we need pointers in C ?
Written by
Why do we need pointers in C?
-To allocate memory dynamically
-To refer to the same space in memory from multiple locations. This means that if you update memory in one location, then that change can also be seen from another location in your code
– To navigate arrays
-To obtain and pass around the address to a specific spot in memory
Working of pointers:
The working of a pointer can be best understood with the help of a code.
Consider the below code snippet:
#include <stdio.h> int main(void) { int *numPtr; //Declaring a pointer numPtr of int type int num = 10; //Intialising a normal variable numPtr = # //Intialising numPtr as a pointer to num printf("Address of num variable: %x\n", &num); printf("Address stored in numPtr variable: %x\n", numPtr ); printf("Value of *numPtr variable: %d\n", *numPtr ); return 0; }
In this code, we are creating two variables – a normal variable num that stores the integer 10, and a pointer numPtr that stores the address of num.
When we run this program, we get the following output:
Address of num variable: d58d03c4 Address stored in numPtr variable: d58d03c4 Value of *numPtr variable: 10
num stores the value ten. The address of num is d58d03c4. The pointer numPtr stores this very address i.e. d58d03c4 as it points to num.
To see what value is stored in the variable pointed by numPtr, we make use of the * operator. As we know, printing *numPtr will display 10, as num stores 10.
By this logic, printing num and *numPtr will give the same output.
The below diagram will help to understand how the above code works: