Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ map problem

I have a

 map<char*, int> labels;

thats exhibiting some behavior that I can't wrap my head around at all. For one index it's returning different values for what I'm pretty sure are the same indexes. Heres an example:

earlier in my program, I add an entry as follows:

labels[current->u.bj.target->name] = blockNum + 1;
//Test code

    if (blockNum + 1 == 9)
    {
        stringtest = current->u.bj.target->name;
        cout << "Condition Met" << endl;
        testCond = true;
    }

later on in my program, I do the following

if ((*stringtest) == (*current->u.bj.target->name))
    cout << "Why is this printing the correct val " <<labels[stringtest] << endl;
branchTarget = labels[current->u.bj.target->name];
cout << "Why is this value different" << branchTarget << endl;

as you can tell from the cout statements, labels[stringtest] returns 9, but labels[current->u.bj.target->name] returns 0 despite the fact they both point to the same thing. Can anyone give me an idea whats wrong/how to fix it? I'm almost positive I never put 0 into the map at all.

like image 410
Megatron Avatar asked Dec 05 '25 13:12

Megatron


1 Answers

The problem will probably disappear if you replace map<char*, int> with map<string, int>. That's because comparing two char* objects will only compare the pointers, not the characters, whereas comparing two string objects will compare the characters.

(Don't forget to #include <string>).

like image 135
fredoverflow Avatar answered Dec 08 '25 07:12

fredoverflow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!