*p 和 *&p 有什么区别
What is the difference between *p and *&p
这段代码有问题,
int main()
{
char *p = "example";
printf("%s\n", *&p); This is giving desired output
printf("%s\n", *p); Here giving segmentation fault
return 0;
}
我的问题是这里的 *&p 和 *p 有什么区别,它们在这段代码中是如何工作的?
*&p
实际上与 p
相同并且类型为 char *.
所以这些电话
printf("%s\n", *&p);
printf("%s\n", p);
产生相同的结果。
*p
的类型为 char
,不能与格式说明符 %s
一起使用。否则将它与格式说明符 %s
一起使用会导致未定义的行为
你可以改写
printf("%c\n", *p);
^^
注意并不总是*&p
等同于p
.
例如,您不能将运算符 & 应用于 non-lvalue
。
考虑以下演示程序。
#include <stdio.h>
char * f( void )
{
char *p = "Hello";
return p;
}
int main(void)
{
printf( "%s\n", f() );
// The statement below will not compile if to uncomment it
// printf( "%s\n", *&f() );
return 0;
}
在此程序中,函数 f
返回的临时对象不是左值。
&p
是变量p
的地址,类型char **
。然后值 *&p
取消引用该地址,为变量 p
提供类型 char *
的左值。 *&p
完全等同于 p
.
*p
正在取消引用变量 p
。这为 p
指向的字符提供了类型 char
的左值,在本例中为字符串开头的 'e'
。 (请注意,虽然它是 char
类型,但此值是只读的,因为 p
是指向字符串文字的指针。)
由于默认类型转换,您最终将值 'e'
的 int
传递给 printf
。 printf
将此值视为地址,因为您使用格式说明符 "%s"
,printf
取消引用此指针,这是无效的内存访问..
在这种情况下:
1) p is a char pointer storing the address where is stored first 'e' letter in "example"
2) *p is the value stored at that address stored in p, that means the value 'e'
3) *&p = *(&p) is the value pointed by the address of p then *&p == p
然后给出 1,2,3 :
printf("%s\n", *&p); // is equivalent to printf("%s\n",p) which is OK
printf("%s\n", *p); // is equivalent to printf("%s\n",'e') which is wrong
// because 'e' is interpreted as an address
这段代码有问题,
int main()
{
char *p = "example";
printf("%s\n", *&p); This is giving desired output
printf("%s\n", *p); Here giving segmentation fault
return 0;
}
我的问题是这里的 *&p 和 *p 有什么区别,它们在这段代码中是如何工作的?
*&p
实际上与 p
相同并且类型为 char *.
所以这些电话
printf("%s\n", *&p);
printf("%s\n", p);
产生相同的结果。
*p
的类型为 char
,不能与格式说明符 %s
一起使用。否则将它与格式说明符 %s
一起使用会导致未定义的行为
你可以改写
printf("%c\n", *p);
^^
注意并不总是*&p
等同于p
.
例如,您不能将运算符 & 应用于 non-lvalue
。
考虑以下演示程序。
#include <stdio.h>
char * f( void )
{
char *p = "Hello";
return p;
}
int main(void)
{
printf( "%s\n", f() );
// The statement below will not compile if to uncomment it
// printf( "%s\n", *&f() );
return 0;
}
在此程序中,函数 f
返回的临时对象不是左值。
&p
是变量p
的地址,类型char **
。然后值 *&p
取消引用该地址,为变量 p
提供类型 char *
的左值。 *&p
完全等同于 p
.
*p
正在取消引用变量 p
。这为 p
指向的字符提供了类型 char
的左值,在本例中为字符串开头的 'e'
。 (请注意,虽然它是 char
类型,但此值是只读的,因为 p
是指向字符串文字的指针。)
由于默认类型转换,您最终将值 'e'
的 int
传递给 printf
。 printf
将此值视为地址,因为您使用格式说明符 "%s"
,printf
取消引用此指针,这是无效的内存访问..
在这种情况下:
1) p is a char pointer storing the address where is stored first 'e' letter in "example" 2) *p is the value stored at that address stored in p, that means the value 'e' 3) *&p = *(&p) is the value pointed by the address of p then *&p == p
然后给出 1,2,3 :
printf("%s\n", *&p); // is equivalent to printf("%s\n",p) which is OK
printf("%s\n", *p); // is equivalent to printf("%s\n",'e') which is wrong
// because 'e' is interpreted as an address