C difference char *a Vs char a[]

Difference between char *a and char a[]

char * and char [] both are used to access character array, Though functionally both are same , they are syntactically different. See how both works in order to access string.

A. How Char a[] Works ?

Consider following sample example for storing and accessing string using character array –

char a[] = "HELLO";

In the example – String “Hello” is stored in Character Array ‘a’. Character array is used to store characters in Contiguous Memory Location. It will take Following Form after Initialization. We have not specified Array Size in this example.Each array location will get following values –

a[0] = 'H'
a[1] = 'E'
a[2] = 'L'
a[3] = 'L'
a[4] = 'O'
a[5] = '\0'

It will Looks Like This …

Accessing Individual Element :

Suppose we have to find out a[3] then firstly compiler will check whether ‘a’ is Array or Pointer ? If ‘a’ is Array Variable then It starts at the location “a”, goes three elements past it, and returns the character there.In this method element is accessed Sequentially

B. How Char *a Works ?

String “Hello” will be stored at any Anonymous location in the form of array. We even don’t know the location where we have stored string, However String will have its starting address.

Syntax of Char *a :

char *a = "HELLO";

the above syntax will take following form –

We have declared pointer of type character i.e pointer variable is able to hold the address of character variable. Now Base address of anonymous array is stored in character pointer variable. ‘a’ Stores Base Address of the Anonymous Array [Unknown Array]

Address = [Base Address of Anonymous Array]  + [i]

Accessing Individual Element :

Consider we have to access a[3] then –
In Short if ‘a’ is a pointer, it starts at the location “a”, gets the pointer value there, adds 3 to the pointer value, and gets the character pointed to by that value
[box]In both Cases a[3] returns same Character but Procedure is Different.[/box]