Statement "you dont need to use & in scanf while using %s" might be misleading.
A scanf
format specifier that is about reading in and storing a value always requires a pointer to an object of the respective type. This is usually achieved by unary &
-operator, which returns the address of an object. Yet some types like arrays automatically decay to a pointer to the first element of the array, such that the following code actually passes a pointer:
char text[100] = "";
scanf("%s", text); // array automatically decays to a pointer to the first element.
scanf("%s", &text[0]); // explicitly take the address of the first element
If you do not have an array but a pointer to char, the code changes as follows:
char *text2 = malloc(100);
scanf("%s", text2); // text2 is a pointer, not an array
Again, you do not need an &
, because you already pass the pointer value.
So statement "you dont need to use & in scanf while using %s" is true as %s
always requires a pointer to a sequence of characters, and either you pass an array which automatically decays to a pointer or you pass a pointer directly.
Your code is wrong from two perspectives:
char *a="how are you";
printf("%s",*a);
First, *a
is not a pointer but a single character value ('h'
in your case), which - when converted to a pointer value - will be something like memory address 0x0000001A
. Accessing this yields undefined behaviour / seg fault.
Second, it's a printf
, not a scanf
. If you want a printf, write:
char *a="how are you";
printf("%s",a);
If you want a scanf, write:
char a[100];;
scanf("%s",a);