C Pointer Arithmetic

In the previous chapter you learned about different types of pointers and their usage. In this chapter you will learn how to implement pointers in your code.

As we know that a pointer holds the address of a variable, so changing a pointer's position will allow a programmer to access other memory location. Suppose an integer pointer is pointing to an integer array whose first element is stored in the address 1004. Incrementing the pointer by one position forward using the increment operator will move the pointer to the location 1008 because integers are of 4 bytes in width.

The following program prints content of an array using pointers along with their memory location.

Code

#include<stdio.h>
int main(void)
{
	int arr[] = {10,20,30,40,50};
	
	// integer pointer pointing to the array
	int *ptr = arr;    // or int *ptr = &arr[0]
	int i = 0;
	// calculating no. of elements in the array
	int size = sizeof(arr)/sizeof(arr[0]);
	
	while(i < size)
	{
		printf("%d at %p\n",*ptr,ptr);
		//incrementing ptr
		ptr++;
		//incrementing index
		i++;
	}
	return 0;
}

Output

10 at 0061FEB0
20 at 0061FEB4
30 at 0061FEB8
40 at 0061FEBC
50 at 0061FEC0

The following program prints the content of a character array along with their memory location.

Code

#include<stdio.h>
int main(void)
{
	char arr[] = "hello";
	
	// char pointer pointing to the array
	char *ptr = arr;
	
	//Looping until end of string excluding the '\0'
	while(*ptr != '\0')
	{
		printf("%c at %p\n",*ptr,ptr);
		//incrementing ptr
		ptr++;
	}
	return 0;
}

Output

h at 0061FEBE
e at 0061FEBF
l at 0061FEC0
l at 0061FEC1
o at 0061FEC2

Access an Array Element using Pointers

In an array, a random element can be picked if its index is known. Similarly, a pointer can be used to access a random memory location of an array. The following code demonstrates the usage of pointers to access a random array element.

Code

#include<stdio.h>
int main(void)
{
	int arr[] = {10,20,30,40,50};
	
	// integer pointer pointing to the array
	int *ptr = arr;    // or int *ptr = &arr[0]
	
	// third element 
	int i = 2;
	
	printf("%d\n",ptr[i]);
	
	return 0;
}

Output

30

Edit Content using Pointers

As pointers store the address of a variable, assigning a value to it will change the content of the memory location to which it is pointing to.

Example Code

#include<stdio.h>
int main(void)
{
	int val = 10;
	int *ptr = &val;
	
	//assigning 20 to the pointer
	*ptr = 20;
	
	printf("%d",val);
	
	return 0;
}

Output

20

Trending

C Programming

Remember to follow community guidelines and don't go off topic.