Pointer arithmetic in C programming language

Here we will learn how pointer arithmetic works with pointer variables?

Here, we are taking an example with an integer array; we will declare an integer pointer and initialize the pointer with the base address of integer array.

Consider this example and read the explanation written below the program and output

C program with pointer arithmetic (++) using int array, pointer of array

#include <stdio.h>
int main(){
	//declare an arra
	int arr[]={10,20,30,40,50};
	//declare and initialise pointer
	int *ptr=arr;
	
	printf("arr[0] value: %d, memory address: %p\n",*ptr,ptr);
	++ptr;
	printf("arr[1] value: %d, memory address: %p\n",*ptr,ptr);	
	++ptr;
	printf("arr[2] value: %d, memory address: %p\n",*ptr,ptr);	
	++ptr;
	printf("arr[3] value: %d, memory address: %p\n",*ptr,ptr);	
	++ptr;
	printf("arr[4] value: %d, memory address: %p\n",*ptr,ptr);		
	
	return 0;	
}

Output

arr[0] value: 10, memory address: 0x7fffb273d9f0
arr[1] value: 20, memory address: 0x7fffb273d9f4
arr[2] value: 30, memory address: 0x7fffb273d9f8
arr[3] value: 40, memory address: 0x7fffb273d9fc
arr[4] value: 50, memory address: 0x7fffb273da00

Explanation

In this program, each ++ (increment) expression is adding 1 to the pointer variable (ptr) but pointer variable (ptr) is not moving 1 byte.

Why?

When we add 1 to the pointer, pointer moves sizeof(pointer_data_type) bytes.

For example - if there is an integer pointer and we add 1 into the pointer will move sizeof(int) i.e. 2 or 4 bytes (depends on the system architecture).

In this example pointer variable ptr is an integer type and the sizeof(int) is 4 hence pointer is moving 4 bytes on each ++ operation and accessing the next values from array arr.


Related Tutorials



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.