简体   繁体   中英

why can not use strlen(char[]) to compare a value

#include <stdio.h>
#include <string.h>

int main(void) {

    char words[2][3] = {{'a','b','c'},{'A','B','C'}};

        for(int j= 0 ;j < 2;j++){

            long diff =   0 - (strlen(words[j]));

            printf("%d , %d \n"  ,  (diff <= 0)  ,  (0  -  strlen(words[j]) <= 0 )  );

        }

    return 0;
}

/*

1, 0

1, 0

*/

why? I expected result is 1,1. enter image description here

strlen expects a pointer to a string. A "string" in C is a zero terminated array of characters.

Neither {'a','b','c'} nor {'A','B','C'} arrays are zero terminated. So calling strlen on them is undefined behavior.

You need to put a terminating zero character '\0' (or just 0 for byte strings) after the array that compose the string. So to make execution of your program defined, you have to:

#include <stdio.h>
#include <string.h>
int main(void) {
    char words[2][4] = { // note - include space for zero in size.
        // equal to "abc"
        {'a','b','c','\0'},
        // string literal can be used as initializers too
        // and they are zero teminated
        "ABC"
    };
    for(int j= 0 ;j < 2;j++){
        long diff =   0 - (strlen(words[j]));
        printf("%d , %d \n"  ,  (diff <= 0)  ,  (0  -  strlen(words[j]) <= 0 )  );
    }
    return 0;
}

why diff <= 0 and (0 - strlen(words[j]) <= 0 ) is diffrent?

Because strlen returns an unsigned type size_t , the expression 0 - strlen(words[j]) has unsigned type, so it can't be negative. On substraction from zero unsigned underflow happens and it results in a very big unsigned value.

diff has type long , so it is signed. On diff initialization diff = 0 - (strlen(words[j])); the unsigned result of 0 - (strlen(words[j])) is converted to type long which results in a small negative signed value (on your machine).

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