C++ is one of the most versatile languages in the world. It is used nearly everywhere for everything… systems programming (operating systems, device drivers, database engines, embedded, Internet of Things, etc.)

Enter Header Image Headline Here

Saturday, 15 April 2017

C++ Pointer and Arrays

                                 C++ Pointer and Arrays


Pointers are the variables that hold address. Not only can pointers store address of a single variable,it can also store address of cells of an array.

Consider this example. :



























Suppose, pointer needs to point to the fourth element of an array, that is hold address of fourth array element in above case.

Since ptr points to the third element in the above example, ptr. + 1 will point to the fourth element.

You may think , ptr +1 gives you the address of next byte to the ptr. But it's not correct.

This is because pointer ptr is a pointer to an int and size of int is fixed for a operating system (size in int is 4 byte of 64-bit operating system). Hence, the address between ptr and ptr+1 differs by 4 bytes.

If pointer ptr was pinter to char then, the address between ptr+1 would have differed by 1 byte since size of a character is 1 byte.

Example : Pointer and Arrays

C++ Program to display address of elements of an array using both array and pointers


           #include <iostream>


























Output :
In the above program, a different pointer ptr is used for display the address of array elements arr.

But, array element can be accessed using pointer notation by using same array name arr.                  

 For example : 















Example : Pointer and Arrays

C++ program to display address of array elements using pointer. notation.






















Output :





















You know that, pointer ptr holds the address and expression *ptr gives the value stored in the address.

Simillary, you can get the value stored in the pointerptr + 1 using*(ptr+1).

Consider this code below : 

int ptr[5] = {3, 4, 5, 5, 3};

  • &ptr[0] is equal to ptr and *ptr is equal to ptr[0]
  • &ptr[1] is equal to ptr + 1 and *(ptr+1) is equal to ptr[1] 
  • &ptr[2] is equal to ptr + 2 and *(ptr+2) is equal to ptr[2] 
  • &ptr[i] is equal to ptr + i and *(ptr+i) is equal to ptr[i] 

Example: C++ pointer and Array


C++ Program to insert and display data entered by using pointers notation.




























Output : 







0 comments:

Post a Comment

Popular Posts

Recent Posts

Categories

Unordered List

Text Widget