Difference between Array and Pointers in C.

CServer Side ProgrammingProgramming

Array in C is used to store elements of same types whereas Pointers are address varibles which stores the address of a variable. Now array variable is also having a address which can be pointed by a pointer and array can be navigated using pointer.r Benefit of using pointer for array is two folds, first, we store the address of dynamically allocated array to the pointer and second, to pass the array to a function. Following are the differences in using array and using pointer to array.

  • sizeof() operator prints the size of array in case of array and in case of pointer, it prints the size of int.

  • assignment array variable cannot be assigned address of another variable but pointer can take it.

  • first value first indexed value is same as value of pointer. For example, array[0] == *p.

  • iteration array elements can be navigated using indexes using [], pointer can give access to array elements by using pointer arithmetic. For example, array[2] == *(p+2)

Example (C)

 Live Demo

#include <stdio.h>
void printElement(char* q, int index){
   printf("Element at index(%d) is: %c\n", index, *(q+index));
}
int main() {
   char arr[] = {'A', 'B', 'C'};
   char* p = arr;
   printf("Size of arr[]: %d\n", sizeof(arr));
   printf("Size of p: %d\n", sizeof(p));
   printf("First element using arr is: %c\n", arr[0]);
   printf("First element using p is: %c\n", *p);
   printf("Second element using arr is: %c\n", arr[1]);
   printf("Second element using p is: %c\n", *(p+1));
   printElement(p, 2);
   return 0;
}

Output

Size of arr[]: 3
Size of p: 8
First element using arr is: A
First element using p is: A
Second element using arr is: B
Second element using p is: B
Element at index(2) is: C
raja
Published on 06-Jan-2020 11:02:30
Advertisements