Codementor Events

Pointers and its use

Published Nov 13, 2019

Pointer in C is a very vast topic and its concepts are still unclear to many developers.

Before explaining pointer I want you to visualize pointer as blocks
[][][][][][][][]
a b c d e f g h
here, each aplhabet is representing a block of memory which stores peice of data.
We all know, pointer is a memory location.

Lets take below example
char *ptr;
*ptr = 'h';

Note :above piece will not work as 'h' need some memory location to be stored

'h' must be stored at some character type(1 byte) memory location.

So, 'h' needs a storage area, which is yet not available to 'ptr' pointer, thats why, if we need to store anything into a pointer first we need to allocate memory to it. And memory allocation should be as of data type of pointer.

Lets malloc the ptr and try to store 'h'
char *ptr;
ptr = malloc(2 * sizeof(char));
ptr = 'h';
here, we malloced 2
sizeof(char), which means 2 bytes of memory is allocated.
Question might arises why 2 bytes when we only need 'h' in memory, will discuss this later.

The above piece of code will work and store 'h' at some random memory location. Lets suppose ptr get memory block a and b then memory must look like
[h][][][][][][][]
a b c d e f g h
Write now, b block will have some junk and printing of pointer might result into a junk data after 'h'.
So, what all majors we need to take?
For this,

  1. we need to null terminate the same,
  2. pointer must be NULL
  3. free the pointer, Other wise, pointer 'ptr' will continue to point to b block even after execution completion.

Whole piece of code must look like
char *ptr;
ptr = malloc(2 * sizeof(char)); //Allocation of 2 byte to ptr
*ptr = 'h'; // 'h' is stored at current position of pointer, // let suppose its block a
ptr++; //need to increment position of pointer,so that // it start pointing to block b
*ptr = '\0'; // this will store null at block b
ptr = NULL; //Before freeing pointer always remember to // NULL the pointer
free(ptr); // this will free pointer from block b.

Single Pointer is nothing but is a 1-D array, which stores data at indexes.
They only concept which differs is memory.
Memory for array is allocated from stack and memory for pointer is allocated from heap.
For pointer memory allocation is dependent on 'C' fuction used for allocation, like if we use calloc(), it will take contiguous memory from heap, but if using malloc, it may or may not take contiguous memory from heap.

Pointer Uses includes if we want to use memory from heap but not from stack we will use pointer.

Memories concepts will be covered in some other post.

Discover and read more posts from shikha
get started
post commentsBe the first to share your opinion
Show more replies