All printf()
calls you use are incorrect, except for the second one, because either the relative argument or the used conversion specifier is wrong.
This invokes Undefined Behavior:
Quote from C18, 7.21.6.1/9 - "The fprintf function":
"If a conversion specification is invalid, the behavior is undefined.288) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined."
printf("%c\n",p);
When you attempt to print the value of the object the pointer points to, you have to use the dereference operator (*
) preceding the pointer object. Else you attempt to print the value of the pointer - the address of the object the pointer point to. And due to this operation, you using the wrong conversion specifier of %d
instead of %p
to print the value of a pointer.
The corrected program is:
#include<stdio.h>
int main(void)
{
char c[]= "Suck It Big";
char *p = c;
printf("%c\n", *p); // Prints the first element of array c.
printf("%c\n", p[3]); // Prints the fourth element of array c
printf("%c\n", *(++p)); // Prints the second element of array c
printf("%p\n", (void*) p); // Prints the address held in p / first element of c.
printf("%p\n", (void*) &p[3]); // Prints the address of the fourth element of c.
}
Note, that the cast to void*
is necessary to make the program conforming to the C standard.
Output:
S
k
u
0x7fff1d3a133d // Address defined by system
0x7fff1d3a1340 // Address defined by system