[英]change a pointer that I passed inside a function in C
我有這段代碼(希望)將成為一個單鏈列表實現。
#include <stdio.h>
#include <stdlib.h>
struct NODE{
int d;
struct NODE *next;
};
int addNode(int n, struct NODE **root);
int main(){
struct NODE *root = NULL;
addNode(3, &root);
printf("%i\n", root->d);
getch();
return 0;
}
int addNode(int n, struct NODE **root){
if(*root == NULL){
*root = malloc(sizeof(struct NODE));
*root->d = n;
*root->next = NULL;
return 0;
}
}
當我運行它時,我在addNode函數中收到“請求成員'd'的信息,而不是結構或聯合”。 與“下一個”部分相同。 如果相反,我將函數更改為此:
int addNode(int n, struct NODE **root){
struct NODE *temp;
if(*root == NULL){
*root = malloc(sizeof(struct NODE));
temp = *root;
temp->d = n;
temp->next = NULL;
return 0;
}
}
它工作正常。 我的問題是; 為什么我必須創建溫度? 據我了解,在代碼的第一個版本中,我傳遞了一個指向root的指針,這樣就不會出現“按引用傳遞”的問題,並且它在運行時也不會出現問題...這是什么錯誤?
(*root)->d = n;
(*root)->next = NULL;
它是一個運算符優先級問題。 使用()
可以修復它。
運算符優先級。
*root->d = n;
被解析為
*(root->d) = n;
但是你想要
(*root)->d = n;
請參考操作員優先級表 。 ->
運算符的優先級比*
(取消引用)運算符的優先級高,這是導致您出錯的原因。
由於運算符優先級,* root-> d被解釋為*(root-> d)而不是(* root)-> d。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.