Home > Back-end >  Class pointer printing to console
Class pointer printing to console

Time:03-06

This is probably a quick fix but I can't find a solution. I am unsure why, but the code output to this C program is just nothing, instead of printing "tag1" to the console. Am I using pointers incorrectly?

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#include <string>

class tag {
public:
    string tag_name;
    tag* child;
};

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
    
    tag* tag1;
    tag1->tag_name = "tag1";
    cout<<tag1->tag_name;
    
    return 0;
}

CodePudding user response:

The problem is that the pointer named tag1 has not been initialized. And you're dereferencing this uninitialized pointer when you wrote tag1->tag_name = "tag1"; which leads to undefined behavior.

Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.

So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.

So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.

For example, here the program crashes but here it doesn't crash.

Solution

To solve this you you have make sure that this pointer points to some tag type object. For example,

class tag {
public:
    std::string tag_name;
    tag* child;
};

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
    //create object of type tag 
    tag obj; 
    obj.tag_name = "original tag";
    std::cout<<obj.tag_name<<std::endl;
    
    //create pointer to object obj
    tag* tag1 = &obj;
    tag1->tag_name = "tag1";
    std::cout<<tag1->tag_name;
    
    return 0;
}

Demo


1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.

CodePudding user response:

tag* tag1 is a pointer to an object of type tag, it's not itself an object. Now, as it is not initialized to anything, this will cause undefined behavior. So to fix your problem you can write:

tag* tag1 = new tag();

This basically creates a new object of type tag and then makes tag1 point to that object.

Now your code should work perfectly.

Also you should not use the following in your code:

using namespace std;

..as it's considered as a bad practice. For more info on this, look up to why is using namespace std considered as a bad practice.

  • Related