我正在尝试使用一个结构“学生”和另一个结构“堆栈”来制作一个小链表,该结构包含学生结构和指向下一个元素的指针。访问冲突写入位置0xCDCDCDCD
但是我不断地收到一个存储器访问错误。我双检查,以确保所有的指针被初始化(只有一个指针,Stacktop,初始化为NULL)
这里有结构定义:
#include <stdio.h>
#include <string>
#include <iostream>
#include <stdlib.h>
using namespace std;
struct students
{
int matnr;
string name;
};
struct stack
{
students stud;
stack *next;
};
typedef struct stack Stack;
typedef Stack *ptrStack;
void push(students s);
students pop();
int isEmpty();
void printStack(students stud);
这里是推送功能(这使崩溃的PROGRAMM)
#include "stack.h"
ptrStack Stacktop = NULL;
void push(students s)
{
ptrStack stack = (ptrStack)malloc(sizeof(Stack));
if (stack == NULL)
{
cout << "!!FIN!!" << endl;
return;
}
stack->stud = s;
stack->next = Stacktop;
Stacktop = stack;
return;
}
这里是主要的:
#include "stack.h"
students readStuds()
{
students s;
cout << "Enter Student name: " << endl;
cin >> s.name;
cout << "Enter Matr Nr: " << endl;
cin >> s.matnr;
return s;
}
int main()
{
char c;
do {
push(readStuds());
cout << "Continue Entering Students? " << endl;
cin >> c;
cout << "----------------------" << endl;
cout << "----------------------" << endl;
} while (c != 'q');
cout << " POPPING STACK " << endl;
cout << " ............. " << endl;
while (isEmpty())
{
printStack(pop());
}
}
不要在C++中使用malloc – Borgleader
您正在通过malloc或new使用已分配的内存,但从未由应用程序编写[何时以及为什么OS将内存初始化为0xCD ,0xDD等malloc/free/new/delete?](http://stackoverflow.com/q/370195/995714) –
C语言不包含'cin'或'cout',所以你的C标签是不适当。即使它们有相似之处,它们也不是*相同的语言。请仅使用与您要问的问题实际相关的标签;否则会破坏标签系统的用途。谢谢。 –