Join Regular Classroom : Visit ClassroomTech

Pointer to an array in C

Pointer to an array points to the 0th element of the array instead of pointing to the individual elements it point to the whole array. In case of pointer to an array we are creating a pointer variable defining the number of integer that is basically used to group or is generally used to mention the number of elements per row of an a array.

Syntax:

datatype *pointer_var_name[array size]

Example:

int(*q)[4]

If we assigned an array of 4 integers to this pointer variable, then if we increment q, the q will be incremented as q = previous address stored into q + (size of int)*no of integers in the array[4]

So, if the base address of the array is 5000 as there are 4 elements in the array, if we consider the int size is 4 bytes [considering for 64 bit machine] then q++ result [5000+(4*4)]=5016

Let’s take an example to understand.

Example

/* C program to understand pointer to an array */
/* www.codewindow.in */

#include <stdio.h>

// Driver code
int main() {

	int a[][4]={5, 7, 6, 9, 4, 6, 3, 1, 2, 1, 6, 8};  //a two dimensional array having 4 columns and rows will automatically be 3

	int *p;                // declaring an int pointer
	int(*q)[4];            // q is a pointer to an array of 4 integers 
	p=(int *)a;		// explicitly typecasting a to integer pointer and storing into another int pointer	variable
	q=a; 			//a is assigned to q
	printf("%u %u\n", p, q);  
	
	++p;
	++q;
	printf("%u %u\n", p, q);
	
	return 0;
}

Output

2320607808 2320607808
2320607812 2320607824

Explanation
As there are 4 elements in each row of the array, if we consider the int size is 4 byte then q++ results [2320607808+(4*4)]=2320607824 and p++ results [2320607808+4]=2320607812

Follow Us


You Missed

Also Checkout