When you declare char string[]="Hello"
you declare an array of characters.
string
points to the first element of the array. *
is known as the dereferencing operator.
Suppose ptr
is an integer pointer. *ptr
will give you the content of the memory location pointed by the pointer ptr
. At the time of declaration you have to declare it as int *ptr
so that the compiler knows that ptr is a pointer variable(hence the asterix there).
when you execute printf("first character is %c", *my_pointer);
the function expects a character corresponding to %c
. The declaration char *string
and char string[]
are roughly(not completely) equivalent. my_pointer
is a character type pointer. *my_pointer
dereferences my_pointer
. In other words *my_pointer
gives you the content of my_pointer
ie the first character in your string.
However a %s
expects a string (a character array, which is basically a char pointer) as the corresponding argument in printf
. *my_pointer
is a character. my_pointer
can be treated as a string. Also print
will treat the argument as a string and print the who;e thing till \0
.
my_pointer=array_of_words
“assigns” the value of array_of_words
to my_pointer
.
array_of_words[]
is an array, so the value of array_of_words
is basically the memory address of the first element of the array(notice the absence of []). In effect my_pointer
now points to the first element of the array.
Hope this explains it.
4
solved why pointer variable with asterisk and without asterisk behave differently in printf?