gpt4 book ai didi

c - 使用指向指针的指针实现堆栈

转载 作者:太空宇宙 更新时间:2023-11-04 00:43:33 25 4
gpt4 key购买 nike

我正在实现一个双指针运动的小程序这是主程序:

#include <stdio.h>
#include "serial.h"
#include "stack.h"

int main(void) {
serial_init();

/* Array to hold stack entries */
int stack[10]={0};
/* Stack pointer */
int *stack_p = stack;

/* Code to call the functions */

push(&stack_p, 1);
push(&stack_p, 2);
push(&stack_p, 3);
push(&stack_p, 4);

printf("popped value: %d\r\n", pop(&stack_p));
printf("popped value: %d\r\n", pop(&stack_p));
printf("popped value: %d\r\n", pop(&stack_p));
printf("popped value: %d\r\n", pop(&stack_p));
}

void push(int **sp, int value) {
/* Implement it */
}

int pop(int **sp) {
/* Implement it */
}

我实现了推送功能,貌似没问题。但是,pop 只返回最后一个元素,然后返回 10

void push(int **sp, int value) {
/* implemented it*/

int *pt;
pt=&value; // Store the value to the pointer

printf("Push value is is %d\r\n", *pt);
sp = &pt; // associate the pointer to the pointer of pointer
++(*pt);
}

int pop(int **sp) {
/* implemented it */
int value;
int *pt;
pt=&value;

sp = &pt;
*pt--;

return value;
}

最佳答案

你的 push 和 pop 函数过于复杂而且完全错误:

你想要这个:

void push(int **sp, int value) {
**sp = value; // put value onto top of the stack
(*sp)++; // increment stack pointer
}

int pop(int **sp) {
(*sp)--; // decrement stack pointer
return **sp; // return value which is on nthe op of the stack
}

你的错误推送代码在评论中解释:

void push(int **sp, int value) {
int *pt;
pt=&value; // here you put the pointer to the local variable value
// into pt, but local variables disappear as soon
// as the function has finished

// the printf is the only thing one more or less correct
// but you could just print directly 'value' like this:
// printf("Pushed value is %d\r\n", value);
//
printf("Push value is is %d\r\n", *pt);

sp = &pt; // this only assigns the pointer to the local variable pt to
// the local variable sp

++(*pt); // here you increment actually the local variable
// value which is pointless
}

顺便说一下:没有必要将整个堆栈初始化为零,尽管它可能在调试过程中有所帮助。所以你可以这样写栈的声明:

int stack[10];  // no initialisation necessary

适合你的练习:

解释为什么没有必要将堆栈的所有元素初始化为零的确切原因。

关于c - 使用指向指针的指针实现堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55167311/

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