c - 未能在 C 中实现一个非常简单的堆栈数组

标签 c segmentation-fault stack

#include <stdio.h>
#include <stdlib.h>
static int top = 0;
static char stack[100];    

void push(char thing2push)
{
if (top == 100){
    fprintf(stderr, "Too many things in the stack");        
    exit(1);
}else{  
    stack[top] = thing2push;
    top++;
    }
}

然后我主要有:

 extern void push(int);
 push(1);

但这会导致“段错误”。我猜它与内存违规有关,但我不知道如何修复它。

编辑这是完整的代码:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
extern int pop();
extern void push(int);

void readTag(){ 
    int tagVal = getchar();
    int poppedVal;
    if (getchar() == '/'){
            poppedVal = pop();
            if (poppedVal != tagVal){
                 printf("NOT Valid");
                 exit(1);
             }
    }else{
       push(1);
    }

}


 int main(int argc, char * argv[])
 {
      int ch;
      while ((ch = getchar()) != EOF) {
          if (!(isalpha(ch) || ch == '<'))
          continue;
          readTag();
       }
       printf("Valid");     
       exit(0);
 }

这是堆栈:

#include <stdio.h>
#include <stdlib.h>
static int top = 0;
static char stack[100];

int isEmpty()
{
        return !(top);
}

char pop()
{
        if (isEmpty()){
            fprintf(stderr, "Stack is empty");      
        exit(1);
    }   
    top--;
   return stack[top+1];
}

 void push(char thing2push)
 {
    if (top == 100){
           fprintf(stderr, "Too many things in the stack");     
        exit(1);
    }else{  
        stack[top] = thing2push;
        top++;
    }
}

最佳答案

top 变量始终指示堆栈中的next 条目(就​​您的程序而言,它显然不包含有效元素)。所以你不应该读取 stack[top] 的值。

函数pop发生段错误,当top达到100时:

top--;               // top == 99
return stack[top+1]; // return stack[100]

您应该写入 stack[top],但从 stack[top-1] 读取。

您可以保留函数 push 不变,只更改函数 pop:

top--;
return stack[top];

关于c - 未能在 C 中实现一个非常简单的堆栈数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22356733/

相关文章:

c - 了解 scanf 在这段代码中所做的事情

c - C/C++ 中文件读取的重命名文件的扩展问题

c - 如何在打印结构字符串时修复 "Segmentation fault"?

linux - 在 asm 中调用函数时出现段错误

c++ - 为什么尽管具有相同的算法和数据结构,但另一个解决方案的效率却提高了 10 倍?

data-structures - 堆栈和队列 : Which is simpler to implement using arrays?

c - 为什么 gdb 得到错误的 "optind"变量值?

c - 函数在独立模式下工作正常,但在较大的程序中则不行

c - 段错误(核心已转储)堆栈

c++ - 进行循环分析的最佳方法