2017-10-06 66 views
0

所以我有函數top()返回堆棧的頂部(實現爲鏈表)。它返回一個Node結構。當我嘗試訪問返回結構的變量時,出現錯誤。訪問返回的結構變量

typedef struct nodeStrcut{ 
    int x,y; 
    struct nodeStrcut* next; 
}Node; 

Node top(Node** head){ 
    return **head; 
} 

void push(Node** head, int x, int y){ 
    //create a new node to contain the value 
    Node* newPtr = (Node*) malloc(sizeof(Node)); 
    newPtr->x = x; 
    newPtr->y = y; 
    newPtr->next = *head; 
    *head = newPtr; 
} 

int main(int argc, char **argv){ 
    Node* stack; 
    stack = NULL; 
    push(&stack, 3, 3); 
    push(&stack, 2, 3); 
    push(&stack, 3, 5); 
    printf("Node value: %d, %d\n", (pop(&stack)).x, (pop(&stack)).y); 
    return -1; 
} 

然後我得到以下錯誤:

project.c: In function ‘main’: 
error: request for member ‘x’ in something not a structure or union 
error: request for member ‘y’ in something not a structure or union 

我知道,我可以用重新建立了新> X要獲取值,但我需要有從的停止返回值的函數疊加。幫助將不勝感激。

+0

你爲什麼不返回一個指針一個節點? –

+0

'(pop(&stack))。x'->'(top(&stack))。x'? –

+0

你沒有在顯示的代碼中聲明'pop()'(你已經定義並因此聲明瞭'top()')。你有不確定的行爲,因爲你在參數列表中調用了兩次'pop()'到'printf()',並且你不能確定調用哪個順序。'top()'函數可以被安全地調用兩次;它會每次都返回相同的值,直到其他內容改變堆棧。 –

回答

1
Node* newPtr = (Node*) malloc(sizeof(Node)); 

有沒有必要施放malloc的回報,這是沒有必要的。請參閱:Do I cast the result of malloc?。以下是足夠的:

Node *newPtr = malloc (sizeof *newPtr); 

的地址headtop變化的,所以沒有必要通過的head地址,例如

Node top (Node *head){ 
    return *head; 
} 

你不應該從main()返回值。有兩種定義的回報:

EXIT_SUCCESS: 0 
EXIT_FAILURE: 1 

See What should main() return in C and C++?

把它完全:

#include <stdio.h> 
#include <stdlib.h> 

typedef struct nodeStrcut{ 
    int x,y; 
    struct nodeStrcut* next; 
} Node; 

Node top (Node *head){ 
    return *head; 
} 

void push (Node **head, int x, int y) { 

    Node *newPtr = malloc (sizeof *newPtr); 
    newPtr->x = x; 
    newPtr->y = y; 
    newPtr->next = *head; 
    *head = newPtr; 
} 

int main (void) { 

    Node *stack = NULL; 

    push (&stack, 3, 3); 
    push (&stack, 2, 3); 
    push (&stack, 3, 5); 

    printf ("Node value: %d, %d\n", (top (stack)).x, (top (stack)).y); 

    return 0; 
} 

示例使用/輸出

$ ./bin/stacktop 
Node value: 3, 5 
0

您不需要傳入指向top()中指針的指針。將功能定義從Node top(Node** head)更改爲Node top(Node* head)就足夠了。

那麼現在就需要調用以下(不含拼寫錯誤)時的stack地址傳遞:

printf("Node value: %d, %d\n", (top(stack)).x, (top(stack)).y); 
1

我想這只是一個錯字(的pop代替top),這樣你實際上調用不返回Node類型的庫函數。寫printf("Node value: %d, %d\n", top(&stack).x, top(&stack).y);它應該按預期工作。

+0

你應該可以使用'top(&stack).x'而不用額外的括號。 –