Reputation:
I am working on the small program below in order to understand binary trees a bit better. I simply wanted to make sure that the pointer *padre
is being assigned correctly, however nothing prints to the console and I think it has to do with me not understanding how pointers work. Please help.
#include <stdio.h>
#include<iostream>
using namespace std;
class Nodo {
public:
Nodo(int valor) {
dato = valor;
izquierdo = 0;
derecho = 0;
}
int dato;
Nodo* izquierdo;
Nodo* derecho;
};
void Agregar(Nodo** padre, Nodo* hijo) {
if ( !*padre ) {
*padre = hijo;
printf("valor: %i", &(*padre)->dato);
return;
}
}
int main() {
Nodo* padre = new Nodo(5);
Agregar(NULL, padre);
}
Upvotes: 0
Views: 112
Reputation: 4283
You're invoking undefined behaviour by accessing a nullptr: you're passing NULL
as the first argument to Agregar
. Fixing up your code to get the expected printout of the node's value looks like this:
#include <cstdio>
class Nodo {
public:
Nodo(int valor) {
dato = valor;
izquierdo = 0;
derecho = 0;
}
int dato;
Nodo* izquierdo;
Nodo* derecho;
};
void Agregar(Nodo** padre, Nodo* hijo) {
if ( !*padre ) {
*padre = hijo;
printf("valor: %i", (*padre)->dato); // pass dato by value not by address
return;
}
}
int main() {
Nodo* padre = new Nodo(5);
Nodo* temp = nullptr;
Agregar(&temp, padre); // first argument must not be nullptr
}
Upvotes: 1