我试图编写一个程序来检查平衡的括号,但是当我尝试初始化堆栈/数组时,我得到一个错误的访问(代码= 1,地址0x0)。
以下是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
#define MAX_STRING_LEN 1000
#define MAX_STACK_SIZE 5000
typedef char StackElement;
typedef struct Stack{
StackElement *content;
int maxSize;
int top;
}Stack;
void Init(Stack*stack);
void Destroy(Stack*stack);
void Push(Stack*stack, StackElement element);
StackElement Pop(Stack*stack);
int IsEmpty(Stack*stack);
int IsFull(Stack*stack);
/*
* A new stack variable is initialized. The initialized
* stack is made empty. MaxSize is used to determine the
* maximum number of character that can be held in the
* stack.
*/
void Init(Stack *stack)
{
StackElement *newContent;
/* Allocate a new array to hold the content.*/
newContent = (StackElement*)malloc(sizeof(StackElement)* MAX_STACK_SIZE);
if (newContent == NULL) {
printf("Insufficient memory to initialize stack.\n");
exit(1);/* Exit, returning error code.*/
}
stack->content = newContent;
stack->maxSize = MAX_STACK_SIZE;
stack->top = -1;
}
int CheckBalancedParentheses (char* expression){
int i = 0;
Stack *stack;
Init(stack);
if (strcmp(&expression[i], ")") == 0 || strcmp(&expression[i], "]") == 0 || strcmp(&expression[i], "}") == 0){
return FALSE;
}
for (i = 0; i < strlen(expression); i++){
if (strcmp(&expression[i], "(") == 0 || strcmp(&expression[i], "[") == 0 || strcmp(&expression[i], "{") == 0){
Push(stack, expression[i]);
}
}
return TRUE;
}
所有这些行都发生了错误的访问(我单独测试了它们):
stack->content = newContent;
stack->maxSize = MAX_STACK_SIZE;
stack->top = -1;
我无法弄清楚为什么它会给我一个糟糕的访问权限,我们将不胜感激任何帮助/建议!
先谢谢你。
答案 0 :(得分:1)
您已经定义了一个堆栈指针,这不会分配内存。
在调用Init:
之前,需要在CheckBalancedParentheses中使用malloc语句/* Allocate memory for our stack */
Stack* stack = malloc( sizeOf(Stack) );