Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ class with char pointers returning garbage

I created a class "Entry" to handle Dictionary entries, but in my main(), I create the Entry() and try to cout the char typed public members, but I get garbage. When I look at the Watch list in debugger, I see the values being set, but as soon as I access the values, there is garbage. Can anyone elaborate on what I might be missing?

#include  <iostream>

using  namespace  std;

class Entry
{
    public:
            Entry(const char *line);
            char *Word;
            char *Definition;
};

Entry::Entry(const char *line)
{
    char tmp[100];
    strcpy(tmp, line);

    Word = strtok(tmp, ",") + '\0';
    Definition = strtok(0,",") + '\0';
}

int  main()
{
    Entry *e = new Entry("drink,What you need after a long day's work");
    cout << "Word: " << e->Word << endl;
    cout << "Def: " << e->Definition << endl;
    cout << endl;

    delete e;
    e = 0;

    return  0;
}
like image 361
JMP Avatar asked Nov 30 '22 10:11

JMP


1 Answers

Word and Definition both point into tmp, which has gone out of scope and so contains garbage.

like image 60
Paul R Avatar answered Dec 05 '22 04:12

Paul R