gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:31:06 24 4
gpt4 key购买 nike

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

由于 top 正在被修改,我将通过引用传递指针 top 。但即便如此,它也不起作用。我哪里出错了?

P.S.:我知道这不是实现 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*/

}

最佳答案

Since top is getting modified, I am passing the pointer top by reference.

但是你不会用这个事实来改变顶部。这是一个解决方案(我尚未编译或测试它,因此它可能包含错误):

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);

堆栈.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;
}

关于c - 函数调用期间指针到指针不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24792648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com