【发布时间】:2015-08-15 06:18:21
【问题描述】:
我正在尝试使用一个结构“students”和另一个结构“stack”创建一个小型链表,其中包含学生结构和指向下一个元素的指针。
但是,我不断收到内存访问错误。我仔细检查以确保所有指针都已初始化(只有一个指针,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);
这里是推送功能(不断地让程序崩溃)
#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(除非你绝对知道你在做什么)
-
您正在使用通过 malloc 或 new 分配的内存,但从未由应用程序写入 When and why will an OS initialise memory to 0xCD, 0xDD, etc. on malloc/free/new/delete?
-
C语言不包含
cin或cout,所以你的C标签不合适。它们不是同一种语言,尽管它们有相似之处。请仅使用与您提出的问题实际相关的标签;否则会破坏标签系统的目的。谢谢。