如何解决如何解决“抛出异常:写访问冲突”
我正在编写一个简单的程序,该程序将创建一个链表,然后将输入作为每个学生的姓名和 GPA。
#pragma warning(disable:4996)
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string>
using namespace std;
struct studentList {
struct student* student;
struct studentList* next;
}*list = NULL;
struct student {
char* name;
double gpa;
};
int main() {
studentList* headPointer = NULL; //create a head pointer to the list
studentList* tailPointer = NULL; //create a tail pointer to the list
studentList* displayPointer = NULL;
studentList* stuListPtr = NULL;
student* stuPtr = NULL;
char choice;
double gpa;
char* tempName = NULL;
int count = 0;
while (1) {
cout << "1. Add student record\n";
cout << "2. display student records\n";
cout << "3. Count number of records\n";
cout << "4. Exit\n";
cin >> choice;
switch (choice) {
case '1':
count++;
stuListPtr = (studentList*)( malloc(count * sizeof(studentList)));
stuPtr = (student*)(malloc(count * sizeof(student)));
cout << "What is the name of the student?\n";
cin >> tempName;
stuListPtr->student->name = tempName;
cout << "What is his/her GPA?\n";
cin >> stuListPtr->student->gpa;
if (headPointer == NULL) {
headPointer = stuListPtr;
tailPointer = stuListPtr;
}
else if (headPointer != NULL) {
tailPointer->next = stuListPtr;//memory of the SL type
}
stuListPtr->next;
break;
当我输入'1'作为选择case 1的选项后,程序要求我输入名字,输入名字后,程序自动结束。我试图在名称为 tempName 的行上放置一个断点,弹出错误“抛出异常:写访问冲突”。任何人都可以帮我解决这个问题吗?
附言
stuListPtr->student->name = tempName;
下的绿色下划线表示“取消引用 NULL 指针 'stuListPtr'”
解决方法
欢迎来到 SO,你分配了你的指针,但你没有初始化它。由于这个原因,这条线失败了:
stuListPtr->student->name = tempName;
因为 stuListPtr
指向一个已分配但没有数据的地方。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。