引自免费微信小程序:皆我百晓生
首先,从提供的信息来看,程序崩溃的原因是由于试图访问无效内存地址,这通常意味着存在数组越界、指针未初始化或野指针等问题。
在您的代码中,StrCompare函数的逻辑有问题。它只比较了当前出栈的字符与栈中的某个索引(即输入的i)的字符,而不是检查整个字符串是否对称。为了修复这个问题,我们需要遍历字符串的一半,并检查每个字符与其对应位置的字符是否相等。
下面是修改后的代码,我已经调整了StrCompare函数,使其正确地检查字符串是否对称:
#include<stdio.h>
#include<cstdlib>
#include<windows.h>
#define MAXLEN 100
typedef char DataType;
typedef struct
{
DataType data[MAXLEN];
int top;
}SeqStack;
void InitStack(SeqStack*S)
{
// 初始化栈
S->top = -1;
}
int StackEmpty(SeqStack*S)
{
// 判断是否空栈
if(S->top == -1)
return 1;
else
return 0;
}
int StackFull(SeqStack*S)
{
// 判断是否栈满
if(S->top == MAXLEN - 1)
return 1;
else
return 0;
}
int Push(SeqStack*S,DataType x)
{
if(StackFull(S))
{
printf("栈满,不可入栈");
return 0;
}
else
{
// 入栈
S->top++;
S->data[S->top] = x;
printf("%5c",S->data[S->top]);
return 1;
}
}
int Pop(SeqStack*S,DataType*x)
{
if(StackEmpty(S))
{
printf("栈空,不可出栈");
return 0;
}
else
{
// 出栈
*x = S->data[S->top];
S->top--;
return 1;
}
}
int GetTop(SeqStack*S,DataType*x)
{
if(StackEmpty(S))
{
printf("栈空,无栈顶");
return 0;
}
else
{
// 取栈顶元素
*x = S->data[S->top];
}
}
void StrCompare(SeqStack*S,DataType*x,int n)
{
// 判断一个字符串是否是对称串
int mid = n / 2;
for(int i = 0; i < mid; i++)
{
if(*x != S->data[n - 1 - i])
{
printf("此字符串不是对称串\n");
return;
}
}
printf("此字符串是对称串\n");
}
int main()
{
int i,n,m,flag;
SeqStack S;
DataType x;
// 进行入栈操作
printf("请输入要入栈的元素个数:");
scanf_s("%d",&n);
printf("请输入%d个入栈元素的值:",n);
for(i=0;i<n;i++)
{
scanf_s("%c",&x);
flag=Push(&S,x);
}
if(flag==1)
// 进行出栈操作
// printf("\n请输入要出栈的元素个数");
// scanf_s("%d",&m);
printf("出栈元素为:");
for(i=0;i<n;i++)
{
Pop(&S,&x);
printf("%5c",x);
StrCompare(&S,&x,n); // 传递正确的字符串长度
}
system("pause");
return 0;
}
这个修改过的版本应该能正确地检查字符串是否对称。请注意,在实际项目中,建议使用更标准的库文件,例如 <stdio.h> 而不是 <stdlib.h>。另外,使用 scanf_s 是安全一些的选择,但这里使用标准的 scanf 也应该没有问题。