I have the following code:
int main(int argc, char **argv)
{
printf("%s\n",*argv);
int test = 5;
char* p;
*pint = test;
p = "banana";
printf("%s\n",p);
printf("%d\n",*pint);
}
Why is it that I have to write p="banana"
and not *p="banana"
but for an integer, it needs to be *pint
, otherwise it will only print the address of the integer? Shouldn't p
print the address of "banana" ?
You are comparing array and integer variable behavior !
p = "banana";
You are assigning base address of string "banana" to pointer p.
And the printf function prototype is
int printf( const char *restrict format, ... );
printf("%s\n",p);
Above statement implies that you are passing pointer p as a argument to a function printf which holds address of string "banana"
You are printing with %s
. This prints a C string taking an input as the address of the first byte of the string.
If you print it with %p
, you will get the address.
printf("%p\n",p);
A C-style string is an array of characters terminated by '\\0'
. So when you assign a string to it, this is what it looks like;
char p[] = {'b', 'a', 'n', 'a', 'n', 'a', '\\0'};
So when say, you print out p
using format specifier %s
, it will continue to print the remaining characters till it reaches the null terminating character.
Doing this printf("%c", *p)
will only print the first character.
Using an integer, if you do this;
int p[] = {1,2,3,4,5};
And print it out;
print("%d", *p);
You only get the first integer in the array.
Note; each format specifier has its kind of value it accepts. That is why they're called format specifiers
PS:
I've edited my answer based on user2079303 and alk's comments!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.