【发布时间】:2014-09-19 23:07:16
【问题描述】:
我正在尝试编写一个程序来检查平衡括号,但是当我尝试初始化堆栈/数组时,我得到了错误的访问(代码=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;
我无法弄清楚为什么它给了我一个错误的访问权限,任何帮助/建议将不胜感激!
先谢谢你了。
【问题讨论】:
-
stack->content:stack为 NULL。 -
@BLUEPIXY
stack未初始化。 -
@AlexD 未经证实。
-
我正在尝试使用 Init 对其进行初始化,并使用 Stack *stack 声明它。 Init 函数正在初始化它,或者至少我认为。
-
@PM 试试
Stack stack;Init(&stack);或Stack *stack=malloc(sizeof(*stack));Init(stack);
标签: c xcode xcode5 exc-bad-access