noobuntu noobuntu - 5 months ago 18
C++ Question

Cannot convert type to type* - C++ compile error

I am trying to create a dynamic array of type 'T' that contains an array of type 'X'. In order to access attributes of T from X, I tried creating a pointer in struct X that points to T. This is the code I have:

struct WireSeg; // Forward declaration

struct Track { // Type X in above description
int trackNum;
bool used;
WireSeg* parentWireSeg;

struct WireSeg { // Type T in above description
int xCoord;
int yCoord;
char flag;
char orientation;
Track* track;

typedef WireSeg* WireSegPtr

int main (void) {
WireSegPtr wireSeg;
wireSeg = new WireSeg[5];
for (int i =0; i<5; i++) {
wireSeg[i].track = new Track[3];
for (int j =0; j<3; j++) {
wireSeg[i].track[j].parentWireSeg = wireSeg[i];

I get the compile error:

error: cannot convert ‘WireSeg’ to ‘WireSeg*’ in assignment

I don't get it.
has been declared as a
type pointer and
is also an element in the
array and is a pointer (isn't it?).

I tried playing around with it and declared
to be of type

struct Track {
int trackNum;
bool used;
bool flag;
WireSeg parentWireSeg;

This gave me error:

‘struct Track’ has no member named ‘parentWireSeg’.

This makes no sense to me either since struct
does have
as an element! Can someone please explain this? Am I not allowed to have a pointer in
that points to

I can probably use inherited classes (can I?) for this but I would prefer if someone told me what is wrong with my method?


Try changing the line where you do the assignment to:

wireSeg[i].track[j].parentWireSeg = &wireSeg[i];

You see, wireSeg is of type WireSeg*, so when you dereference it by doing *wireSeg or wireSeg[0] or wireSeg[i], you get something that is of type WireSeg. If you want the address of the object instead of the object itself, so you can make a pointer, you need to add the address operator (&).