2011-05-06 102 views
3

我如何取消引用指针,因为我在填充函数中打包结构并传递指针以发送如何取消引用它?我得到的分割故障我做了什么取消引用指针

#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); 
} 
+6

你尝试过发送(创建)吗? – RedX 2011-05-06 12:20:54

+3

从一个非常快速的扫描...尝试'发送(创建);'不'发送(*创建);' – 2011-05-06 12:21:10

回答

10

send(*create)将发送实际的结构对象,而不是一个指针。

send(create)将发送指针,这是你需要的。

当函数声明的参数包含星号(*)时,需要指向某个东西的指针。当你将该参数传递给另一个需要另一个指针的函数时,你需要传递参数的名称,因为它已经是一个指针了。

当您使用星号时,您取消了对指针的引用。这实际上发送了“create指向的内存单元”,实际的结构而不是指针。

2

线

send(*create); 

应该

send(create); 

创建变量已经是一个指针,没有必要为*

1

你不会问你这个问题,已经要求编译器帮助你(没有冒犯!)。编译器是你的朋友。启用它的警告。对于

gcc -Wall yourcode.c 

例如GCC给你

yourcode.c: In function ‘fill’: 
yourcode.c: 11:5: warning: implicit declaration of function ‘send’ 
yourcode.c: At top level: 
yourcode.c:15:5: warning: return type defaults to ‘int’ 
yourcode.c:22:5: warning: return type defaults to ‘int’ 
yourcode.c: In function ‘send’: 
yourcode.c:26:5: warning: control reaches end of non-void function 
yourcode.c: In function ‘main’: 
yourcode.c:19:5: warning: control reaches end of non-void function 

现在你知道你应该写一个原型功能send或移动它是第一个使用上述定义。由于编译器假定默认返回类型为send,您显然忘了指定它(因为您没有任何返回值,因此显然为void)。对于main返回类型int

return 0; 

丢失。

随着该修饰的编译器会告诉你

yourcode.c: In function ‘fill’: 
yourcode.c:12:5: error: incompatible type for argument 1 of ‘send’ 
yourcode.c.c:7:6: note: expected ‘struct xxx *’ but argument is of type ‘struct xxx’ 

,你会发现你在

send(*create); 

它取消引用指针一个冗余*。注意:您不想取消引用您的指针,因为您必须将指针转发到send而不是该值。将该行更改为

send(create); 

etVoilà。