[英]dereference a pointer
當我在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);
}
send(*create)
將發送實際的struct對象,而不是指針。
send(create)
將發送指針,這就是你需要的。
當函數聲明的參數包含星號(*)時,需要指向某事物的指針。 然后,當您將該參數傳遞給另一個需要另一個指針的函數時,您需要傳遞參數的名稱,因為它已經是一個指針。
使用星號時,您取消引用指針。 這實際上發送了“ create
點的內存單元格”,實際的結構而不是指針。
這條線
send(*create);
應該
send(create);
create變量已經是一個指針,不需要*
如果你曾要求編譯器幫助你,你就不會問這個問題(沒有冒犯!)。 編譯器是你的朋友。 啟用它的警告。 例如GCC用
gcc -Wall yourcode.c
給你
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à。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.