Array of Pointers in C

Previous
Next

Array of Pointers:

  • Declaration of array variable of any pointer type can hold multiple addresses.
  • These pointers either can points to all elements of single array or pointers to different arrays.
#include<stdio.h>
int main()
{
	int arr[4] = {10, 20, 30, 40};
	int* ptr[4];
	int i;
	
	for(i=0 ; i<4 ; i++)
	{
		ptr[i] = &arr[i];
	}
	
	printf("Array elements are : \n");
	for(i=0 ; i<4 ; i++)
	{
		printf("%d \n", *ptr[i]);
	}
	return 0;
}
  • In the above code, we store and access the element using indexing.
  • We can also process elements and store addresses using pointers(no indexing).
#include<stdio.h>
int main()
{
	int arr[4] = {10, 20, 30, 40};
	int* ptr[4];
	int i;
	
	for(i=0 ; i<4 ; i++)
	{
		*(ptr+i) = arr+i ;
	}
	
	printf("Array elements are : \n");
	for(i=0 ; i<4 ; i++)
	{
		printf("%d \n", **(ptr+i));
	}
	return 0;
}
#include<stdio.h>
void main()
{
	char* s[5] = {"one", "two", "three", "four","five"};
	int i=0,j=4;
	char* t;
	while(++i < j--)
	{
		t = s[i];
		s[i] = s[j];
		s[j] = t;
	}
	printf("%s",*(s + ++i));
}
Previous
Next

Add Comment

Courses Enquiry Form