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





Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.




Comments and Discussions





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com (2015-2018), Some rights reserved.