gpt4 book ai didi

c - 为什么堆栈不传递命令行的输入

转载 作者:行者123 更新时间:2023-11-30 15:22:58 25 4
gpt4 key购买 nike

如何找到错误所在?它打印出嵌套不正确,我认为它没有将任何内容插入堆栈,但 peek 函数给出了错误。我真的很困惑为什么 vim 不突出显示任何错误并且它仍然可以编译。

          #include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

#define MAXLEN 512


typedef struct {
char element[MAXLEN];
int size;
} stack;

stack init (void)
{
stack S;
S.element[0] = 'c';
S.size = -1;
return S;
}

bool is_empty( stack S );
char peek( stack S );
bool is_full( stack S );
stack push(stack S, char ch);
char pop (stack S);
void exit_stack_overflow(void);
void exit_stack_underflow(void);
void exit_incorrect_nesting(void);


int main(void)
{

char ch;
stack S;
char buf[MAXLEN]; // should i use this or have it in the struct
int i = 0;
S = init();
int length = sizeof(buf)/sizeof(buf[0]);
printf("Enter parentheses and/or braces: ");


fgets(buf, length, stdin); //reads an entire line into stack, no more chars than length
while (1) {
if(buf[i] == '\n'){
break;
}




ch = buf[i];
i++;


if(ch == '"'){
push(S, ch);
if(peek(S) != '\''){

if (peek(S) == '"') {
pop(S);

}
else{
push(S, ch);


}
}


}
else if(ch == '\''){
if(peek(S) != '"'){
if (peek(S) == '\'') {
pop(S);
}
else
push(S, ch);
}
}
else if(peek(S) != '\'' && peek(S) != '"') {
switch(ch) {
case '(':
case '{':

push(S, ch);

break;
case ')':

if (is_empty(S) || pop(S) != '(')
exit_incorrect_nesting();
break;

case '}' :
if (is_empty(S) || pop(S) != '{'){

exit_incorrect_nesting();

}
break;
}
}
}


if (is_empty(S))
printf("Nesting is correct\n");
else {

exit_incorrect_nesting();

}

return 0;
}


bool is_empty( stack S )
{
return (S.size == 0);
}

bool is_full( stack S )
{
return (S.size == MAXLEN - 1);
}

char peek( stack S )
{

return S.element[S.size];
}

stack push( stack S , char ch )
{
if (is_full(S)) {
fprintf(stderr, "push: Full stack\n");
return S;
}
++S.size;
S.element[S.size] = ch;
return S;
}

char pop( stack S )
{
int i = S.size;
if(is_empty(S)) {
fprintf(stderr, "pop: Empty stack\n");
return S.element[i];
}
--S.size;
return S.element[i];
}

void exit_stack_underflow(void)
{
fprintf(stderr, "Stack Underflow\n");
exit(EXIT_FAILURE);
}
void exit_stack_overflow(void)
{
fprintf(stderr, "Stack Overflow\n");
exit(EXIT_FAILURE);
}

void exit_incorrect_nesting()
{
printf("Nesting is NOT correct\n");
exit(EXIT_SUCCESS);
}

最佳答案

一个主要问题是您将堆栈结构按值传递给所有函数,这意味着该结构被复制并且在函数内部完成的所有更改都会进行在副本上,而不是原件上。

C 不支持通过引用传递,但可以使用指针进行模拟。

例如,push 可以这样修改:

void push( stack * S , char ch )
{
if (is_full(S)) {
fprintf(stderr, "push: Full stack\n");
return;
}
++S->size;
S->element[S->size] = ch;
}

并像这样调用

push(&S, ch);

所有功能都需要类似的修改。

关于c - 为什么堆栈不传递命令行的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28957526/

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