Pato05
Pato05

Reputation: 356

Variable stuck into If

I'm trying to learn C++ and I'm creating some useless application to test. I'm working with const char and arguments, and in this code I can't get the title string.

const char* title = "";
if (argc >= 3) {
    string tittle(argv[2]);
    title = tittle.c_str();
}

Please help me!

Upvotes: 0

Views: 54

Answers (1)

R Sahu
R Sahu

Reputation: 206627

The problem is that when you use

    title = tittle.c_str();

you are left with a dangling pointer. Instead of const const* title, use std::string title.

std::string title;
if (argc >= 3) {
    title = argv[2];
    cout << "true";
}

If you need to a char const* later in your program, you can use title.c_str(). Hopefully you won't need it.

Upvotes: 6

Related Questions