Difference between pointer and array in C


The details about a pointer and array that showcase their difference are given as follows.

Pointer

A pointer is a variable that stores the address of another variable. When memory is allocated to a variable, pointer points to the memory address of the variable. Unary operator ( * ) is used to declare a pointer variable.

The following is the syntax of pointer declaration.

datatype *variable_name;

Here, the datatype is the data type of the variable like int, char, float etc. and variable_name is the name of variable given by user.

A program that demonstrates pointers is given as follows.

Example

 Live Demo

#include <stdio.h>
int main () {
   int a = 8;
   int *ptr;
   ptr = &a;
   printf("Value of variable a: %d
", a);    printf("Address of variable a: %d
", ptr);    return 0; }

The output of the above program is as follows.

Value of variable a: 8
Address of variable a: -2018153420

Array

An array is a collection of the same type of elements at contiguous memory locations. The lowest address in an array corresponds to the first element while highest address corresponds to the last element. Array index starts with zero(0) and ends with the size of array minus one(array size - 1).

Output

The following is the syntax of array.

type array_name[array_size ];

Here, array_name is the name given to an array and array_size is the size of the array.

A program that demonstrates arrays is given as follows.

Example

 Live Demo

#include <stdio.h>
int main () {
   int a[5];
   int i,j;
   for (i = 0;i<5;i++) {
      a[i] = i+100;
   }
   for (j = 0;j<5;j++) {
      printf("Element[%d] = %d
", j, a[j] );    }    return 0; }

Output

The output of the above program is as follows.

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104

Updated on: 26-Jun-2020

565 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements