Answer: Let’s, first, see their declarations,
char name; /* 'name' a character array declared */ char alphabet; char *cp = &alphabet; /* 'cp' pointer-to-character points to alphabet */
and now analyse them. When compiler comes across the statement
it allocates block of 20 bytes of memory in continuous locations, then creates array name ‘name’ and sets this to the beginning of the array. Therefore array is said to be vector. To confirm amount of memory allocated to ‘name’ we can use ‘sizeof operator’ as:
printf("Amount of memory allocated to array name[%d] is %d bytes.\n", 20, sizeof(name));
and when it reaches the statement
char *cp = &alphabet;
allocates a block of memory, 8 bytes on Linux System, names it ‘cp’ which is ptr-to-char and initializes it with address of character variable ‘alphabet’. Pointer, like other variable types, is said to be scalar.
printf("pointer-to-char 'cp' takes %d bytes of allocation.\n", sizeof(cp));
Note that, on Linux System, pointer variable irrespective of its type, is allocated 8 bytes of memory.
Let’s turn to analyse contents of the two, viz. array ‘name’ and pointer-to-char ‘cp’,
is an array of 20 characters. Array ‘name’ can’t have address as its contents. Pointer-to-char ‘cp’, contains address of character variable ‘alphabet’.
Well! As we just observed that pointer contains address as value. for example,
printf("pointer-to-char 'cp' contains address %p of character variable " "'alphabet'.\n", cp);
What will happen if we assign ‘cp’ address of some another character, for example,
char initial = 'X'; cp = &initial; /* 'cp' is assigned address of 'initial' */
‘cp’ now points to character variable ‘initial’ in the memory. This indicates that ‘cp’ can be assigned address of any character variable.
An array name also is an address or precisely a pointer constant, a constant address points to some fixed location in the memory. Like other constants, value of pointer constant can’t be modified i.e. statements like
isn’t valid. However, ‘cp’ can be used to point to where array ‘name’ points,
cp = name; /* type of array 'name' is pointer-to-char */
‘cp’ and ‘name’ both now point to array ‘name’.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.