函数调用期间指针指针不起作用?

时间:2014-07-16 23:42:36

标签: c pointers pointer-to-pointer

我正在尝试使用辅助函数编写一个单独的文件来进行堆栈操作。我想通过引用将堆栈顶部作为参数传递给主文件中的堆栈操作。

由于top被修改,我通过引用传递指针顶部。但即便如此,它也无法运作。我哪里错了?

P.S。:我知道这不是实现Stack的最佳方式,但我只想了解它为什么不起作用。

// Stack.h

void print(stacknode **P)
{

    stacknode *S;
    S=*P;

    printf("Printing stack from top to bottom...\n");
    stacknode *temp=S;
    while(temp != NULL)
    {
        printf("%d\t", temp->data);
        temp=temp->next;
    }
    printf("\n");
}


void push(stacknode **P, int n)

{

    stacknode *S;
    S=*P;
    stacknode *new=(stacknode *)malloc(sizeof(stacknode));
    new->data=n;
    new->next=S; 
    S=new;
    print(&S);

}

// main.c中

main()
{
    printf("Creating new stack...\n");
    stacknode *S=NULL;

    printf("Pushing first number....\n");
    push(&S, 2);

    print(&S);/*Prints nothing*/

}

1 个答案:

答案 0 :(得分:0)

  

由于top被修改,我正在将指针顶过   参考

但是你没有用这个事实改变顶部。这是一个解决方案(我没有编译或测试它,所以它可能包含错误):

Stack.h :(仅在头文件中声明,无代码)

typedef struct stacknode stacknode;
struct stacknode {
    stacknode* next;
    int data;
};

void print(stacknode* top); // no need for ptr ref
void push(stacknode** ptop);

Stack.c:

#include "Stack.h"
#include <stdio.h>

void print(stacknode* top)
{
    printf("Printing stack from top to bottom...\n");
    for (stacknode* p = top; p; p = p->next)
    {
        printf("%d\t", p->data);
    }
    printf("\n");
}

void push(stacknode** ptop, int n)
{
    stacknode* p = malloc(sizeof *p); // don't cast malloc in C
    if (!p)
        /* handle out of memory */;
    p->data = n;
    p->next = *ptop; 
    *ptop = p;
    print(p);
}

main.c中:

#include "Stack.h"
#include <stdio.h>

int main(void) // declare return type
{
    printf("Creating new stack...\n");
    stacknode* S = NULL;

    printf("Pushing first number....\n");
    push(&S, 2);

    print(S);
    return 0;
}