我正在尝试使用一个结构"学生"和另一个结构"堆栈"创建一个小的链表,其中包含学生结构和指向下一个元素的指针.
但是我经常不断收到内存访问错误.我仔细检查以确保所有指针都已初始化(只有一个指针,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);
Run Code Online (Sandbox Code Playgroud)
这是推送功能(不断崩溃程序)
#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;
}
Run Code Online (Sandbox Code Playgroud)
以下是主要内容:
#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());
}
Run Code Online (Sandbox Code Playgroud)
}
这个:
ptrStack stack = (ptrStack)malloc(sizeof(Stack));
Run Code Online (Sandbox Code Playgroud)
分配足够的内存来保存struct stackaka Stack,但是malloc()没有做任何事情来初始化返回的内存.所以,特别是,string你的新内部stack包含随机垃圾,然后由你解释cin >> s.name,并假设string它是有效的,它不是,所以代码失败.
解决方案 - ptrStack stack = new Stack改为使用.更好的是,编写适当的构造函数/析构函数,复制构造函数,赋值运算符等...