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

Home » C programming language

C pointer to an array

Here, we will learn how to declare, initialize and assign pointer to an array?

We all are aware about array “Array is the group of similar type of values” for example if there are 5 integer values, we can store them in an integer array.

Pointer to an array is the pointer of array variable.






Declaration of pointer to array

    data_type *pointer_variable;

Initialization of pointer to array

    pointer_variable=&array_variable[0];
    OR
    pointer_variable=array_variable;

Let’s consider the declaration and initialization of pointer to integer array

1) Declare integer array with the number of elements

    int arr[5];

2) Declare integer pointer to point the array

    int *ptr;

3) Initialize pointer with the base address of array

    ptr= &arr[0];
    OR
    pt= arr;

4) Initialization with the pointer declaration

    int *ptr= &arr[0];
    OR
    int *ptr= arr;

Let’s consider the program to read and print the integer array elements using integer pointer (pointer to array)

#include <stdio.h>

int main()
{
	int arr[5];
	int *ptr=&arr[0];
	int i;
	
	printf("Enter array elements:\n");
	for(i=0; i<5; i++)
	{
		printf("Enter element [%d]: ",i+1);
		scanf("%d",(ptr+i));
	}
	
	printf("Array elements are:\n");
	for(i=0; i<5; i++)
	{
		printf("Element [%d]: %d\n",i+1, *(ptr+i));
	}
	
	return 0;
	
}

Output

    Enter array elements: 
    Enter element [1]: 100
    Enter element [2]: 200
    Enter element [3]: 300
    Enter element [4]: 400
    Enter element [5]: 500
    Array elements are: 
    Element [1]: 100
    Element [2]: 200
    Element [3]: 300
    Element [4]: 400
    Element [5]: 500

Dynamic array initialization using malloc()

Syntax

data_type *pointer_variable = (data_type*) malloc (N * sizeof(data_type));

Here, N is the number of elements

Example

int *ptr = (int*) malloc(5*sizeof(int));

C program to read and print the array elements where number of elements should be enter at run time

#include <stdio.h>
#include <stdlib.h>

int main()
{
	int i,n;
	int *ptr;
	
	printf("Enter total number of elements: ");
	scanf("%d",&n);
	
	//pointer initialization
	ptr=(int*)malloc(n*sizeof(int));
	
	printf("Enter array elements:\n");
	for(i=0; i<n; i++)
	{
		printf("Enter element [%d]: ",i+1);
		scanf("%d",(ptr+i));
	}
	
	printf("Array elements are:\n");
	for(i=0; i<n; i++)
	{
		printf("Element [%d]: %d\n",i+1, *(ptr+i));
	}
	
	return 0;
	
}

Output

    Enter total number of elements: 5 
    Enter array elements: 
    Enter element [1]: 100
    Enter element [2]: 200
    Enter element [3]: 300
    Enter element [4]: 400
    Enter element [5]: 500
    Array elements are: 
    Element [1]: 100
    Element [2]: 200
    Element [3]: 300
    Element [4]: 400
    Element [5]: 500

COMMENTS