char *stack[13];
char INteger[100];
int top = -1;
int main () {
int current = 0;
while (current < 2) {
Yfunc();
printf("cell zero %s \n", stack[0]);
printf("cell one %s \n", stack[1]);
void Yfunc() {
printf("Please enter a string: \n");
scanf("%s", INteger);
push(INteger);
}
}
char *push(char input[]) {
top++;
stack[top] = input;
}
基本上,用户应该键入一个字符串,比方说“牛”。然后将该字符串推入堆栈(可行)。但是,当我第二次按下时,堆栈变得一团糟。我假设我不能多次scanf(INteger)?如果没有,对此有什么解决方法?
所以您的stack
正在保存内存地址,但实际上不复制内容。解决方案可能是这样:
#include<stdio.h>
#include<string.h>
char stack[13][100];
char INteger[100];
int top = -1;
void push(char* input) {
memcpy(stack[++top], input, 100);
}
void Yfunc() {
printf("Please enter a string: \n");
scanf("%s", INteger);
push(INteger);
}
int main () {
int current = 0;
while (current++ <= 2) {
Yfunc();
printf("cell zero %s \n", stack[0]);
printf("cell one %s \n", stack[1]);
}
}