求助关于访问内存冲突的问题
#include <stdio.h>
#include<conio.h>
#include <malloc.h>
/*top位置*/
int top = -1;
typedef struct{
short int row;
short int col;
short int dir;
} Element;
int stackSize = 10;
/*分配*/
Element* elements = (Element*)malloc(sizeof(Element) * stackSize);
/*压栈操作*/
void push(Element element)//要做一个判断操作
{
if(top == stackSize - 1)
{
Element * temp = (Element *)malloc(stackSize * 2);
if(temp == NULL)
printf("错误");
for(int i = 0; i < stackSize; ++i)
{
//printf("为什么呀%d\n", (elements + i)->dir);
*(temp + i) = *(elements + i);
}
stackSize = stackSize * 2;
free(elements);
elements = temp;//elements是固定了的 不能在那个了 只能改变其指针的指向了
}
elements[++top] = element;
}
Element pop()
{
if(top == -1)
printf("堆栈已空\n");
//这个是临时对象
Element elm = elements[top--];
return elm;
}
int main()
{
for(int i = 0; i < 20; ++i)
{
Element elm;
elm.col = i;
elm.row = i;
elm.dir = i;
push(elm);
}
for(int i = 0; i < stackSize; ++i)
{
Element e = pop();
printf("%d\n", e.dir);
}
return 0;
}
当push压入栈时 在 pop出问题 我总觉得应该是elements = temp;导致的问题,因为temp是一个临时对象。当运行完了就生命周期没了,但把地址赋给elements了呀
[解决办法]