简体   繁体   English

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

[英]Pointer-to-pointer not working during function call?

I am trying to write a separate file with helper functions for stack operations. 我试图编写一个带有帮助函数的单独文件进行堆栈操作。 I want to pass the stack top by reference as an argument to stack operations from the main file. 我想通过引用将栈顶作为参数传递给主文件中的栈操作。

Since top is getting modified, I am passing the pointer top by reference. 由于top被修改,因此我通过引用传递了top指针。 But even then, it is not working. 但是即使那样,它仍然无法正常工作。 Where am I going wrong? 我要去哪里错了?

PS: I know that this is not the best way to implement Stack, but i just wanted to understand why it is not working. PS:我知道这不是实现Stack的最佳方法,但是我只是想了解为什么它不起作用。

//Stack.h //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.c

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

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

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

}

Since top is getting modified, I am passing the pointer top by reference. 由于top被修改,因此我通过引用传递了top指针。

But you don't use that fact to change the top. 但是,您不能利用这一事实来改变顶峰。 Here's one solution (I haven't compiled or tested this so it may contain errors): 这是一种解决方案(我尚未对此进行编译或测试,因此可能包含错误):

Stack.h: (declarations only in header files, no code) 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: 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: 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM