2017-10-06 68 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'而不用额外的括号。 –