Zeiger auf NULL ändert sich in CCCCCCCC innerhalb der Klasse?
-
bin des schreibens müde. es ist 4 uhr
header:
#include <iostream> class Foo { private: int *p; public: Foo(); void move(); };
quellcode:
#include "foo.h"; Foo::Foo(){ int *p = NULL; std::cout << "test1:" << p << std::endl; } void Foo::move(){ std::cout << "test2:" << p << std::endl; }
main:
Foo obj; obj.move();
ausgabe:
test1: 00000000
test2: CCCCCCCCwarum ist das so? ich will dass der zeiger stets auf NULL zeigt.
sonst stürzt mein programm immer ab wegen der falschen NULL-Abfrage
-
xBlackKnightx schrieb:
warum ist das so?
Weil...
xBlackKnightx schrieb:
quellcode:
#include "foo.h"; Foo::Foo(){ int *p = NULL; // ... lokal im Konstruktor ist. std::cout << "test1:" << p << std::endl; } void Foo::move(){ std::cout << "test2:" << p << std::endl; }
Machst du...
class foo_t { private: int *bar; public: foo_t : bar( 0 ) { }; };
... und du wirst glücklich
greetz, Swordfish
-
Weil du mit
int *p = NULL;
im Konstruktor eine lokale Variable p erzeugst und auf NULL setzt. Die lokale Variable hat zwar denselben Namen ist aber nicht die Membervariable der Klasse.
Einfach das int * weglassen, dann sollte es funktionieren.
p = NULL;