if we initialise char pointer as
char *p="Hello";
compiler will search for 6 bytes and will return address of first
byte to pointer p.Then how we can print value of p as
printf("%s",p);
instead of
printf("%s",*p);
Printable View
if we initialise char pointer as
char *p="Hello";
compiler will search for 6 bytes and will return address of first
byte to pointer p.Then how we can print value of p as
printf("%s",p);
instead of
printf("%s",*p);
p is a char*, so the correct format string in printf is %s
Eg printf( "string is %s\n", p );
*p is a char, so the correct format string in printf is %c
Eg printf( "First char of string is %c\n", *p );
I assume that %s will print a char at each address of 'p', starting from the first, until '\0' is found. That is why you pass the location (p) not the contents (*p)
Actually, with the code
the compiler sets aside some memory for the string "Hello", along with all other string constants used in the program. p is then assigned the address of the first char in the string, that is, 'H'.Code:char *p = "Hello";
we do not give address of variable while printing
[code]
char a[]="Hello";
char *p="Hello";
printf("%s",a);
printf("%s",p);//Why we are passing address of first constant string ie.H instead of *p
[\code]
Because you're printing a string of characters, not a single character. If you give printf the value of the address using *p, then how would you propose getting to the next address?Quote:
//Why we are passing address of first constant string ie.H instead of *p
More examples
Code:char a[]="Hello";
char *p="Hello";
printf("%s",a);
printf("%s",p);
printf("%s",&a[0]);
printf("%s",&p[0]);
printf("%s",a+2);
printf("%s",p+2);
printf("%s",&a[2]);
printf("%s",&p[2]);
One that always tickles me is this:
Code:char s[] = "hippo", *p = s+2;
printf("%c\n", p[-1]);