简体   繁体   English

指向常量的指针与打印时指向非常量的指针的行为不同

[英]Pointer to constant behaves differently than pointer to non-constant when printing

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? 为什么我必须写p="banana"而不是*p="banana"但是对于整数,它必须是*pint ,否则它将仅输出整数的地址? Shouldn't p print the address of "banana" ? p不应该打印“香蕉”的地址吗?

  1. You are comparing array and integer variable behavior ! 您正在比较数组和整数变量的行为!

  2. p = "banana";

You are assigning base address of string "banana" to pointer p. 您正在将字符串“ banana”的基地址分配给指针p。

And the printf function prototype is 而printf函数原型是

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" 上面的语句暗示您将指针p作为参数传递给函数printf,该函数包含字符串“ banana”的地址

You are printing with %s . 您正在使用%s进行打印。 This prints a C string taking an input as the address of the first byte of the string. 这将打印一个C字符串,并将输入作为字符串的第一个字节的地址。

If you print it with %p , you will get the address. 如果使用%p打印,您将获得地址。

printf("%p\n",p);

A C-style string is an array of characters terminated by '\\0' . C风格的字符串是由'\\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. 因此,当您说时,使用格式说明符%s打印出p ,它将继续打印其余字符,直到到达空终止符为止。

Doing this printf("%c", *p) will only print the first character. 执行此printf("%c", *p)将仅打印第一个字符。

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: PS:

I've edited my answer based on user2079303 and alk's comments! 我已经根据user2079303和alk的评论编辑了答案!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM