简体   繁体   中英

c++ pass a custom struct through a function

I have been working with this C++ program for a while, and I have figured what exactly is happening, but I haven't figured out how to fix it exactly. Here is what I have set up:

struct entry {
    string foo;
    string bar;
    string num;
};
struct node {
    entry input;
    node* left;
    node* right;
};
node* home = new node;

This code takes place in a separate header file that is included in a main cpp file, which has the following:

home->input.foo="John";
home->input.bar="Doe";
home->input.name="1234";
printAll(home);

This is were the error pops up, trying to pass home through the function printAll in the header file:

void printAll(node* start){
    if(start==NULL) return;
    printAll(start->left);
    cout << start->input.foo;
    printall(start->right);
}

The error that Visual Studio gives me is 0xCDCDCDCD on start . I understand it's not home that is causing the issue, it's start , but I don't understand how to correct this error. I read around and I can assume that start has been thrown into heap memory but it is unintalized. I didn't think this was possible. And I also can guess that C++ doesn't know what start is and how to use it, how would I correct this?

You haven't initialized left or right . In debug builds, Visual Studio will set uninitialized memory to 0xCDCDCDCD . This is obviously not equal to NULL , so your comparison returns false .

As noted in the other answer, the error you are getting may be because you haven't initialized the left and right node as NULL . However you have another error and that is you have created an infinite loop in your printAll.

Your printAll function will first move to the left-most node and print it. After that it will move one node to the right, and, before prints it anything, it'll move to the left again.

The proper way of printing all the nodes is to put list of nodes within a class that keeps track of the first and last node.

Class LList {
    node * startNode;

    void printAll(){
          if (startNode == NULL) 
                return;

          node * currNode = startNode;

         // print all the nodes moving left to right
         _printAll(currNode);
    }

    void _printAll(currNode){
          // print currNode and recursively go to next by calling 
          // _printAll(currNode->right)
     }
}

Additional things to note

  • Of course, you'll want to make printAll public and the rest of the above private.

  • You'll also need a function to add a node to the list. Look up linked lists attributes and methods to see what else you'll need.

  • It's better to avoid structs and use objects in place of them

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM