C 中的值传递
下面的代码可以移植吗?
我只是按值传递指针,并且可以在调用者中更改它!
void foo(void *p)
{
void **pp = (void**)p;
*pp = "hahaha";
}
int main(int argc,char **argv)
{
void *p = NULL;
p = &p;
printf("%p\n",p);
foo(p);
printf("%s\n",(char *)p); // hahaha
printf("%p\n",p);
return 0;
}
Is the following code portable?
I just pass the pointer by value and I can change it in the caller!
void foo(void *p)
{
void **pp = (void**)p;
*pp = "hahaha";
}
int main(int argc,char **argv)
{
void *p = NULL;
p = &p;
printf("%p\n",p);
foo(p);
printf("%s\n",(char *)p); // hahaha
printf("%p\n",p);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,您可以更改指针指向的内容,但您只能这样做,因为您已使指针指向自身:
要回答您的问题,是的,这是可移植的;但不,这通常不是一个好主意。
Yes, you can change what the pointer points to, but you can only do that because you've made the pointer point to itself:
To answer your question, yes this is portable; but no it's not generally a good idea.
您总是按值传递指向指针的指针,当您将其分配给自身以及将其传递给函数时,它看起来就像是单个指针;它起作用只是因为您使该指针指向其自身。
您所做的基本上是这样的:
添加了一些转换和技巧。我想说,“黑暗中的纸牌戏法”,绝对不是放入真正程序中的好主意。
实际回答这个问题:是的,它应该是可移植的,因为标准保证每个数据指针都可以毫无问题地与
void *
进行转换(这就是您在代码中所做的所有事情)时间):(C99,第 6.3.2.3.1 条)
You're always passing a pointer to a pointer by value making it seem a single pointer when you assign it to itself and when you pass it to the function; it works only because you made that pointer point to itself.
What you're doing is basically this:
with some casts and tricks added. "Card tricks in the dark", I'd say, and definitely not a good idea to put in a real program.
To actually reply to the question: yes, it should be portable, because the standard guarantees that every data pointer can be casted to and from a
void *
without problems (which is what you do in your code all the time):(C99, §6.3.2.3.1)
你实际上是在玩指针到指针。您仍然按值传递指针,并且没有欺骗编译器更改调用者的值。您要更改的只是指针指向的值。
除了让你自己和其他程序员感到困惑之外,在现实生活中使用这并不是一个好主意。
You're actually playing with pointers to pointers. You are still passing the pointer by value and you are not fooling the compiler into changing the value of the caller. What you're changing is just the value pointed to by the pointer to the pointer.
Not a very good idea to use in real life apart from confusing yourself and fellow programmers.