读书人

栈的有关问题选自严蔚敏的书。用VC6

发布时间: 2012-03-03 15:33:02 作者: rapoo

栈的问题,选自严蔚敏的书。用VC6运行,弹出内存错误提示
#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
#define ERROR 0
#define OK 1
#define Status int
#define NULL 0
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int SElemType;

typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;

Status InitStack(SqStack &S)
{
S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!S.base)
{
printf("OverFlow! Init error!\n");
exit(ERROR);
}
S.base=S.top;
S.stacksize=STACK_INIT_SIZE;
printf("aaa\n");
*S.top=10; //运行时弹出错误:"0x0040107e"指令引用的"0xcccccccc"内存。该内存不能为"written"。
printf("bbb\n");
S.top++;
return OK;
}

void main()
{
SqStack S;
int i,j;
SElemType k;
k=10;
InitStack(S);
}

[解决办法]
看看top的定义再赋值。
[解决办法]
#include <stdio.h >
#include <stdlib.h >
#define TRUE 1
#define FALSE 0
#define ERROR 0
#define OK 1
#define Status int
#define NULL 0
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int SElemType;

typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;

Status InitStack(SqStack &S)
{
S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!S.base)
{
printf("OverFlow! Init error!\n");
exit(ERROR);
}
S.base=S.top; //你弄反了吧,这里应该是S.top=S.base的吧,可以结帖了吧
S.stacksize=STACK_INIT_SIZE;
printf("aaa\n");
*S.top=10; //运行时弹出错误:"0x0040107e"指令引用的"0xcccccccc"内存。该内存不能为"written"。
printf("bbb\n");
S.top++;
return OK;
}

void main()
{
SqStack S;
int i,j;
SElemType k;
k=10;
InitStack(S);
}

读书人网 >软件架构设计

热点推荐