Right Click to Search

Sunday, August 8, 2024

What is the difference between char *a and char a[]?


How Char a[] Works ?
  • Consider "Hello" String is stored in Character Array 'a'.
  • "HELLO" is Stored in Character Array [ in Contiguous Memory Location.]
  • It will take Following Form after Initialization.
Initialization :
char a[] = "HELLO";
What Happens ?
  • Here Array Size is not Specified .
  • So C Assigns Individual Character to Each Array Location  -
a[0] = 'H'
a[1] = 'E'
a[2] = 'L'
a[3] = 'L'
a[4] = 'O'
a[5] = '\0'
It will Looks Like This ...
How a[3] Works Here ?
  1. Compiler Finds a[3].
  2. Compiler Checks Whether a is Array or Pointer ?
  3. If 'a' is Array Variable then It starts at the location "a", goes three elements past it, and returns the character there
  4. So Access is Sequential.

How Char *a Works ?
  • Consider "Hello" String is stored in Anonymous Character Array.
  • It will take Following Form after Initialization.
Initialization :
char *a = "HELLO";

  • 'a' is Pointer Variable.
  • 'a' Stores Base Address of the Anonymous Array [Unknown Array]
  • Whenever a[3] is to be accessed then In one shot Following Memory Location is Accessed -
Address = [Base Address of Anonymous Array]
          +
          [i]
  • So 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
In both Cases a[3] returns same Character but Procedure is Different.
Related Article :

Tags / Keywords : | , , ,

Stumble
Delicious
Technorati
Twitter
Facebook

0 Comments:

Post a Comment

Your Feedback :This is Growing Site and Your Feedback is important for Us to improve the Site performance & Quality of Content.Feel Free to contact and Please Provide Name & Contact Email

 

Learn C Programming Copyright © 2010 LKart Theme is Designed by Lasantha, Free Blogger Templates