取消引用指针
当我将结构打包到 fill 函数中并传递指针以发送如何取消引用它时,如何取消引用指针?当我在所做的事情中遇到分段错误时
#include<stdio.h>
struct xxx
{
int x;
int y;
};
void fill(struct xxx *create)
{
create->x = 10;
create->y = 20;
send(*create);
}
main()
{
struct xxx create;
fill(&create);
}
send(struct xxx *ptr)
{
printf("%d\n",ptr->x);
printf("%d\n", ptr->y);
}
How can I dereference the pointer as i pack the structure in fill function and pass the pointer to send how to dereference it? as i get segmentation fault in what i have done
#include<stdio.h>
struct xxx
{
int x;
int y;
};
void fill(struct xxx *create)
{
create->x = 10;
create->y = 20;
send(*create);
}
main()
{
struct xxx create;
fill(&create);
}
send(struct xxx *ptr)
{
printf("%d\n",ptr->x);
printf("%d\n", ptr->y);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
send(*create)
将发送实际的结构对象,而不是指针。send(create)
将发送指针,这就是您所需要的。当函数声明的参数包含星号 (*) 时,需要一个指向某些内容的指针。然后,当您将该参数传递给需要另一个指针的另一个函数时,您需要传递参数的名称,因为它已经是一个指针。
当您使用星号时,您取消了指针的引用。这实际上发送了“
create
指向的内存单元”,即实际的结构而不是指针。send(*create)
will send the actual struct object, not a pointer.send(create)
will send the pointer, which is what you need.When your function declaration's arguments contain an asterisk (*), a pointer to something is needed. When you then pass that argument on to another function requiring another pointer, you need to pass the name of the argument, since it is already a pointer.
When you used the asterisk, you dereferenced the pointer. That actually sent the "cell of memory that
create
points to," the actual struct and not a pointer.该行
应该是
创建变量已经是一个指针,不需要 *
The line
should be
The create variable is already a pointer, there is no need for the *
如果您要求编译器帮助您,您就不会问这个问题(无意冒犯!)。编译器是你的朋友。启用它的警告。例如,GCC 给
你
现在你知道你应该为函数
send
编写一个原型,或者将其定义移到第一个用法之上。由于编译器假定send
的默认返回类型,您显然忘记指定它(这里显然是void
因为您没有任何返回值)。对于main
,返回类型int
和 an缺失。
通过上述修改,编译器会告诉您
,您会注意到您有一个多余的 * ,其中
取消引用了您的指针。注意:您不想取消对指针的引用,因为您必须将指针转发到
send
而不是值。将线路更改为et Voilà。
You would not have asked that question if you had asked the compiler to help you (No offense!). The compiler is your friend. Enable it's warnings. For example GCC with
gives you
Now you know that you should have written a prototype for function
send
or moved it's definition above the first usage. And as the compiler assumes a default return type forsend
you obviously forgot to specify it (here apparentlyvoid
as you don't have any return value). Formain
the return typeint
and anis missing.
With the said modifications the compiler will tell you
and you will notice you have one redundant * in
which dereferences your pointer. Note: You do NOT want to dereference your pointer, because you have to forward the pointer to
send
and not the value. Change the line toet Voilà.