C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C programming language

Pointer to an array of integers in C language [Declarations, Initialization with Example]

Learn: How to declare pointer to an array of integers, how to initialize it with the address of an array and how to access array elements using pointer?

As we discussed before that a pointer is a special kind of variable that can store address of another variable.

A pointer can also store the address of an array of integers. Here, we will learn how to declare a pointer to an array of integers, how to initialize pointer with the base address an array and how to access the array elements using the pointer?

1) Declare an array of integers
int arr[]={10,20,30,40,50};

2) Declare an integer pointer
int *ptr;

3) Now, Initialize the pointer with the base address of an array of integers
A) By using array name (it returns the base address of an array)
ptr = arr;
B) By using address of first element of integers array (it also returns the base address of an array)
ptr = &arr[0];

4) Now, pointer contains the base address of an array, to access the particular element, use *(ptr+N). Here, N is the number of element

For example,
*(ptr+0) - will return value of arr[0]
*(ptr+1) - will return value of arr[1]
...
*(ptr+N) - will return value of arr[N]

Consider the following program:

#include <stdio.h>
int main()
{
	int arr[]={10,20,30,40,50};
	int *ptr,loop;
	
	//initialize ptr
	ptr = arr;
		
	//printing the elements
	for(loop=0; loop<5; loop++)
		printf("arr[%d]: %d\n",loop,*(ptr+loop));
	
	return 0;
}

Output

arr[0]: 10
arr[1]: 20
arr[2]: 30
arr[3]: 40
arr[4]: 50






COMMENTS