链表自制类哭诉内存访问问题(C++)
Linked list homemade class cryes about memory access troubles (C++)
在Visual Studio 2013中构建项目时,会显示以下消息:prj.exe中0x00CD5154处未处理的异常:0xC0000005:写入位置0x00000004时发生访问冲突请帮忙。这实际上是一个例子https://www.youtube.com/watch?v=3gZ7F31Mwi0我写的几乎一样。
收割台.h
#ifndef HEADER_H_
#define HEADER_H_
#include <iostream>
#include <string>
//#include <iostream>
//#include <vector>
typedef struct Node
{
int data;
Node* link;
}* NodePtr;
class List
{
public:
List();
~List();
int numberOfElements();
NodePtr getPointer(const int node_number) const;
void addNode(int data_);
//NodePtr head;
private:
NodePtr head;
NodePtr curr;
NodePtr temp;
NodePtr start_index;
};
#endif // !HEADER_H_
来源.cpp
#include "Header.h"
List::List()
{
head = NULL;
curr = NULL;
temp = NULL;//head_ptr = this->Nodes;
start_index = NULL;
}
List::~List()
{
}
int List::numberOfElements()
{
size_t i = 0;
temp = start_index;
while (temp->link != NULL)
{
temp = temp->link;
i++;
}
return i;
}
NodePtr List::getPointer(const int node_number) const
{
NodePtr counter = start_index;
for (size_t i = 0; i < node_number; i++)
{
//%
std::cout << i << std::endl;
//%
if (counter == NULL)
{
std::cout << "last index is " << i << std::endl;
return counter;
}
counter = counter->link;
}
return counter;
}
void List::addNode(int data_)
{
NodePtr n = new Node;
n->data = data_;
n->link = NULL;
if (head != NULL)
{
curr = head;
while (curr != NULL)
curr = curr->link;
curr->link = n;
}
else
{
head = n;
start_index = n;
}
}
main.cpp
#include "Header.h"
int main()
{
using namespace std;
List one;
one.addNode(1);
one.addNode(2);
one.addNode(3);
//cout << (*one.head).data << endl;
//cout << one.getPointer(1)->data << endl;
cin.get();
}
循环之后
while (curr != NULL)
curr = curr->link;
curr
将是NULL
(想想这个,直到你意识到为什么它是真的)。
因此,线路
curr->link = n;
取消引用空指针的位置无效。
你想要
while (curr->link != NULL)
curr = curr->link;
相关文章:
- 从其他类访问类时遇到问题
- 0xC0000005:访问冲突读取位置 0x00000000. 重载 == 运算符的问题
- 初学者问题:如何访问此变量?
- 在C++中循环访问自定义结构列表的小问题
- 从资源视图访问对话框时出现问题
- 在 c++ 中创建和访问 4D 向量时出现问题
- 我遇到了一个糟糕的访问问题
- reinterpret_cast,只读访问,简单的可复制类型,会出什么问题?
- 简单的问题 - 如何从单独的"结构"内的'class'访问变量?
- 在 c++ 中访问列表向量时出现问题
- 消除 C++ 中的菱形问题以访问顶级成员
- C++字符串问题-如何访问字符串元素
- 在单元测试项目中包括 .c 文件,并从多个 cpp 文件访问它而不会出现链接问题
- 如果指针会产生访问私有成员等问题,为什么 C++ 允许指针?
- 访问单例类C++时出现问题
- 嵌套的类成员变量不可访问.链表设置.V、下一个和新的问题
- 通过此指针访问时的成员差异和自身的成员指针(简单的 QT 示例问题)
- 如何解决此C++访问冲突问题
- 操作员问题 - 访问冲突
- 问题5.3:访问/返回/调用动态创建的复选框(?)