在学校的OJ平台提交以下代码,提示运行错误,具体为:Segmentation fault:段错误,检查是否有数组越界,指针异常,访问到不应该访问的内存区域。想问下是哪里的问题,代码在其他dev C++和lightly上运行没有问题。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 20
#define OK 1
#define ERROR 0
typedef int Status;
typedef int SqElemType;
typedef struct {
SqElemType *top;
SqElemType *base;
int StackSize;
} SqStack;
Status InitStack(SqStack *S) {
S->base = (SqElemType *)malloc(sizeof(SqElemType) * STACK_INIT_SIZE);
if (!S->base)
return ERROR;
S->top = S->base;
S->StackSize = STACK_INIT_SIZE;
return OK;
}
Status Push(SqStack *S, SqElemType e) {
if (S->top - S->base >= S->StackSize) {
S->base = (SqElemType *)realloc(S->base, sizeof(SqElemType) * STACKINCREMENT);
if (!S->base)
return ERROR;
S->top = S->base + S->StackSize;
S->StackSize += STACKINCREMENT;
}
*S->top = e;
S->top++;
return OK;
}
Status Pop(SqStack *S, SqElemType *e) {
if (S->top == S->base)
return ERROR;
S->top--;
*e = *S->top;
return OK;
}
int main() {
char str[100001], num[100001] = {0};
int cnt = 0, length = 0;
SqStack S;
InitStack(&S);
while (scanf("%s", str) != EOF) {
length = strlen(str);
for (int i = 0; i < length; i++) {
if (str[i] == '(') {
Push(&S, i + 1); //左括号下标入栈
} else {
Pop(&S, &cnt); //cnt为左括号下标
num[cnt] = i + 1; //num数组第cnt位存对应右括号下标
}
}
for (int i = 0; i < length; i++) {
if (num[i] != 0)
printf("%d %d\n", i, num[i]);
num[i] = 0; //输出完归零
}
}
return 0;
}
