Question

Why does using is_it_valid_color("yellow") work and outputs FOUND IT but using is_it_valid_color(x.c_str()); not work?

I have a feeling it has to do with null terminated strings. The output looks the same in console:

color: 'yellow'
FOUND IT
color: 'yellow'

.

const char *color_names[] = {"yellow", "green", "red"};
const int color_names_SIZE = 3;

void is_it_valid_color(const char* color) {
    cout << "color: '" << color << "'" << endl;

    for(int i = 0; i < color_names_SIZE; ++i) {
        if(color == *(color_names + i)) {   
            cout << "FOUND IT" << endl;
            break;
        }
    }
}



is_it_valid_color("yellow");


string x = "yellow";

is_it_valid_color(x.c_str());
Was it helpful?

Solution

You're not comparing strings, you're comparing pointers to strings.

The first one matches because your linker has coalesced the two strings "yellow" to the same physical pointer to save memory. Their addresses therefore compare as the same.

To compare the actual strings themselves, use strcmp() or similar.

OTHER TIPS

Your comparing memory addresses (in pointers) instead of strings (null terminated sequences of characters) here:

if(color == *(color_names + i)) {   

You need to use std::strcmp instead:

if(std::strcmp(color, *(color_names + i)) == 0) {   

Unless you need to for schooling reasons, it's much clearer to use the subscript operator than to use pointer arithmetic.

Also, c_str() is definitely null terminated.

You shouldn't be use the '==' operator to compare to char*'s

instead you should use the strcmp function in the cstring library

for(int i = 0; i < color_names_SIZE; ++i) {
    if(strcmp(color,color_names[i]) == 0) {   
        cout << "FOUND IT" << endl;
        break;
    }
}

http://en.cppreference.com/w/cpp/string/byte/strcmp

Rewrite the part of the code, where you (allegedly)compare strings.

And have no doubt, c_str() and a char* are both null terminated.

You're comparing pointers not strings. Simple fix is to change

const char *color_names[] = {"yellow", "green", "red"};

to

std::string color_names[] = {"yellow", "green", "red"};

Try not to use pointers anywhere, they only cause trouble, especially when you are learning. You have enough to learn without adding all the complexities of pointers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top