简体   繁体   中英

What is the difference between char word[25]; and char word[25] = “”;?

I'm trying various code to check Palindrome words, sure there are so many ways to code it, I somehow find something that triggers my curiosity but I couldn't find any answer somewhere although the code run good

That's found that there's a slight differences between two array of char wordReverse declaration below.

Could anyone give an explanation of these two declarations?

bool checkPallen(char word[]){
    char wordReverse[25] = ""; //error if used char wordReverse[25];
    int revCount = 0;

    for(int i = strlen(word) - 1; i >= 0; i--){
       wordReverse[revCount] = word[i]; //
       revCount++;
    }

    if(strcmp(wordReverse, word) == 0) return true;
    return false;
}

The difference is that uninitialized local variables have indeterminate values.

When you read from wordReverse ,

strcmp(wordReverse, word)

strcmp takes two strings, ie it expects to find a NUL terminator somewhere.

Your loop that fills wordReverse doesn't terminate it, so you get undefined behavior here.

Fix:

wordReverse[revCount] = '\0';

after the loop.

The version that initializes wordReverse as

char wordReverse[25] = "";

works because it is equivalent to char wordReverse[25] = { '\\0' } , which sets the first element to '\\0' explicitly and all remaining elements to '\\0' implicitly.


NB:

if (X) return true;
return false;

is equivalent to

return !!X; // Returns 1 if and only if X is not 0, and 0 otherwise

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM