我正在学习 C 中的指针,所以我这样做是为了检查我做某事时希望得到的输出。在这里:
int characters(char temp[])
{
printf("\nAddress of string by &temp: %p",&temp);
printf("\nAddress of string by temp: %p",temp);
printf("\nContent of string: %s",temp);
return 0;
}
int main()
{
char s[] = "Prafulla Shahi";
char *t=s;
clrscr();
characters(t);
printf("\nMain\nAddress of string by &s: %p",&s);
printf("\nAddress of string by s: %p",s);
printf("\nContent of string: %s",s);
printf("\nAddress of pointer by &t: %p",&t);
printf("\nAddress of pointer by t: %p",t);
printf("\nContent of pointer: %s",t);
getch();
return(0);
}
我得到的输出是这样的:
Address of string by &temp: 0x7fff4ab45788
Address of string by temp: 0x7fff4ab457b0
Content of string: Prafulla Shahi
Main
Address of string by &s: 0x7fff4ab457b0
Address of string by s: 0x7fff4ab457b0
Content of string: Prafulla Shahi
Address of pointer by &t: 0x7fff4ab457a8
Address of pointer by t: 0x7fff4ab457b0
Content of pointer: Prafulla Shahi
我的问题是: 为什么 temp 数组的地址在 &temp 和 temp 询问时显示两个不同的值?
我的理解是,temp是一个数组变量,但是它有自己的地址(类似于指针t的行为。为什么它的行为不像通常的变量数组s?)。 main()中的数组s[]也是一个数组,只是&s和s调用它的地址是同一个值。
有人能解释一下吗?
最佳答案
char s[] = "Hello world";
s
是一个数组对象(用字符串文字初始化)。数组的地址和数组首元素的地址相同(只是类型不同)。
所以:
(char *) &s == s /* value of the == expression is 1 */
但是:
char *p = "Hello world";
p
是一个指针对象(指向一个字符串文字)。 p
的地址是指针对象的地址,这个地址不同于 p
的值,p
是指向 "Hello世界”
字符串。
所以:
(char *) &p == p /* value of the == expression is 0 */
为了完整地回到您的示例,我还必须添加一个函数声明中的数组参数在 C 中调整为指针类型的参数。所以这两个函数声明是等价的:
int characters(char temp[]) { /* ... */ }
和
int characters(char *temp) { /* ... */ }
这也意味着在 characters
函数中,我们有:
(char *) &temp == temp /* value of the == expression is 0 */
因为 temp
是指针对象而不是数组对象。
关于c - 在 C 中传递字符指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20793343/