Re: Good links for handling with pointers?
Hello,
Alf P. Steinbach schrieb:
Exactly what is the problem?
I often get "segmentation fault" errors because with catchier
constructs, I'm not sure anymore if I should use a reference or a
pointer an so on.
Then often I have the problem that I have a method which should obtain a
non pointer variable, but in this case I only have a pointer to this
variable, and what then?
Let's see my actual example which leads to a "segemntation fault" or
doesn't even compile:
----------------------------------------------------
class Adjazenzmatrix
--------------------
..
..
..
Knoten *knoten[groesse]; //I define a list of size "groesse" of pointers
to "Knoten".
for (int i = 0; i < groesse; i++) {
knoten[i] = new Knoten(i); initialize every element as new Knoten
..
..
..//and so on.....
//This is weird. Here I want to iterate over every element of "knoten",
but....
for (int kBez = 0; kBez < groesse; kBez++) {
findKomponenten(knoten[kBez]); //LINE 178
}
}
-------------------------------------------
....I get the following error message while compiling:
markus@gentoo ~/CPP-Programme/ $ g++ *.cpp -o Main `pkg-config gtkmm-2.4
--cflags --libs`
Adjazenzmatrix.cpp: In member function ?void
Adjazenzmatrix::berechneEigenschaften()?:
Adjazenzmatrix.cpp:178: Fehler: ung?ltige Umwandlung von ?Knoten*? in ?int?
Adjazenzmatrix.cpp:178: Fehler: Argument 1 von ?Knoten::Knoten(int)?
wird initialisiert
Which means something like:
Invalid conversion of "Knoten*" to "int.
Error: Argument 1 of Knoten::Knoten(int) will be initialized.
What does that mean?
Here is the method findKomponenten:
-------------------------------------------------
void Adjazenzmatrix::findKomponenten(Knoten k) {
k.setVisited();
if (k.getNachbarknotenAnzahl() > 0) {
int nachbarCounter = 0;
Knoten neuer = k.getNachbarknoten(nachbarCounter);
while (neuer.isVisited() == false) {
findKomponenten(neuer);
nachbarCounter++;
}
}
}
-------------------------------------------------
So where is there an int I obviously convert to?
Constructor of class Knoten:
------------------------------------------
Knoten::Knoten(int nr) {
knotenNr = nr;
visited = false;
nachbarknoten = new ListT<Knoten>;
}
As you can see, I use a self programmed dynamically list in this class.
Now it's getting complicated for me. Later in this class, I initialize
new ListT-elements which are also "Knoten". I want to access those
elements from Adjazenzmatrix so I have sometimes already pointer with
the deep of two and then I'm not sure anymore how to handle it.
I don't know if I should return a pointer or not or as I already said,
the return values doesn't "fit" to the class which invokes the methods
of the instances because the method returns a non pointer value but in
the invoking class I have a pointer.
I alwasy fight with such problems, so I need to get deeper into the
knowledge of handling with pointer.
Markus