#include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <fstream>
#include <utility>
using namespace std;
struct node
{
int level = -1;
int value = -5;
node *left;
node *right;
};
int array[100][100];
void storetree(node *root, int val);
void printtree();
int main()
{
cout << " u there?" << endl;
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{
array[i][j] = -5;
}
}
ifstream file1;
ifstream file2;
file1.open("tree1.txt");
file2.open("graph1.txt");
node root;
node *root1;
int val1;
int randval;
file1 >> val1;
root.level = 0;
root1->level = 0;
root.value = val1;
root1->value = val1;
array[0][0] = val1;
cout << "made it" << endl;
root1->left->value = -5; // <-- Error happens here
root1->right->value = -5;
root1->left->level = -5;
root1->right->level = -5;
So my error happens when I access root1->left->value, and I get the stack dump error.
Is it impossible to access root1->left->value the way I've written it? Through print statements I've deduced that this is the error. I don't understand pointers well and would appreciate help. :)
答案 0 :(得分:0)
我在下面注释了您的源代码:
...
// Allocate an actual instance of your 'node' struct (local variable, on the stack)
node root;
// This allocates a POINTER variable, which just contains an address.
// The compiler knows that 'root1' will point at 'node' types.
// Note that you've only created a pointer variable here; NOT an actual node.
// Further, you haven't initialized it, so its value is "undefined"
// (you can't assume you know what its value is ... it could be anything).
node *root1;
...
// Set 'level' on the root node to zero
root.level = 0; // This is OK, because root is an actual 'node' struct instance
// Set 'level' ON THE NODE THAT 'root1' POINTS TO to zero
root1->level = 0; // This is not OK, because root1 is a wild (uninitialized) pointer
这是你的第一个问题。你创建了一个指针,但你没有把它指向任何东西。 root1(它引用的地址)的值是 undefined (可能是NULL,可能是该变量所在的内存中的任何内容)
首先,最好在定义局部变量时将其初始化 。 未初始化的变量可能具有未定义的值,并且可以添加无数小时 调试你的生活,你的程序的每次运行都会做与上一次不同的事情。的Bleh。
如果在定义变量时尚未准备好分配实际值, 将它设置为某些已知的值,如0,nullpointer,等等。这样,如果你忘记稍后再设置它,至少你的程序每次都会做错误的事情。
node *root1 = nullptr; // (...or maybe your compiler uses "NULL" or "(void *)0"...)
看起来您将根据从输入文件中读取的内容构建节点树? 如果是这样,那么你几乎肯定会动态地分配节点结构,因为你无法提前知道你需要多少。
// Allocate and initialize a new node struct (on the heap)
root1 = new node();
// Set 'level' ON THE NODE THAT 'root1' POINTS TO to zero
root1->level = 0; // Yay, now this works
变量'root1'现在包含新分配的'node'结构的地址。其余代码应该可以在那里工作。
只是提醒一下,'正确'程序(例如,不泄漏内存的程序)应该最终调用delete
来调用new
所返回的每个指针。
在构建动态分配的node
对象树时,请记住这一点;当你完成所有操作时,你需要在每个上面调用delete
(除了root,你没有动态分配)。