2011-05-06 103 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à。