![](/img/trans.png)
[英]In C, returning a float when sending pointer-to-struct values to a function changes the values of the struct
[英]C function pointer in a struct not changing the values when called
我有一個具有功能的節點結構,它將增加它的valuestruct
node {
int value;
struct node * left;
struct node * right;
void (*incrementValue)(struct node);
};
void incrementNodeValue(struct node this){
this.value ++;
printf("the value is now %d\n", this.value);
}
int main(){
struct node firstLeft = { 5, NULL, NULL, incrementNodeValue };
struct node firstRight = { 15, NULL, NULL, incrementNodeValue };
struct node start = { 10, &firstLeft, &firstRight, incrementNodeValue };
start.incrementValue(start);
printf("%d\n", start.value);
return 0;
}
我的意圖是start.incrementValue會將值從10增加到11。
當我編譯並運行此代碼(無警告)時,它會打印
現在的值是11
10
因此,我知道函數中的值已更改,但是一旦退出該函數似乎就沒有任何效果。
void incrementNodeValue(struct node this)
聲明一個函數,該函數接收struct node
的值 。 該值只是內容的副本。 因此,該功能僅更改副本。 它不會在主例程中更改原始的start
對象。
要更改函數中的原始對象,請更改聲明,以便函數接收struct node
的地址:
void incrementNodeValue(struct node *this)
然后更改呼叫,使其通過地址:
start.incrementValue(&start);
在函數內部,您必須更改代碼以將this
用作指針而不是struct
,因此this.value
變為this->value
。
並且您需要將struct node
內的聲明更改為:
void (*incrementValue)(struct node *);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.