Comparison between pointer and integer in C

后端 未结 8 1306
盖世英雄少女心
盖世英雄少女心 2021-01-05 06:00

I have a bit stupid question about program in C. My compiler says me: warning: comparison between pointer and integer. I really don\'t know why. I only want to writ

相关标签:
8条回答
  • 2021-01-05 06:07

    str[i] is a character. NULL is a pointer. You can't meaningfully compare those two data types (although they may or may not be implemented as the same size of integer internally). That's all the error message means.

    Not that the comparison is not only type-incorrect, it also doesn't do what you probably mean. You seem to assume that a character array with an incomplete initializer would be automatically terminated with a \0 character, but that rule applies to string literals, not to character arrays you create yourself. As it is, you're invoking undefined behaviour.

    0 讨论(0)
  • 2021-01-05 06:10

    Here str[i] is a character an NULL is a pointer, so we can not compare it logically. Use '\0' to compare with str[i] as it is defined to be a null character, so comparing a character str[i] with a null character '\0' is a right method and will not through any warning.

    0 讨论(0)
  • 2021-01-05 06:12

    please write your code like this

    int i = 0; 
    char str[50] = {'s', 'a', 'm', 'p','l','e'}; //only for test 
    while (str[i] != "\0") { 
    putchar(str[i]); 
    i++; 
    } 
    
    0 讨论(0)
  • 2021-01-05 06:13

    NULL is defined as a pointer type, usually (void*)0. This means it should not be compared to characters (which are promoted to integers when used on their own). The problem is with the following: str[i] != NULL. The correct way to do this is compare it to something of the same type, in this case you are looking for the null character, '\0'.

    0 讨论(0)
  • 2021-01-05 06:15

    NULL should only be used in pointer contexts, but here you're comparing it to a character.

    You'd normally want something like:

    while (str[i] != '\0') {
    

    [or, of course, something like puts(str); or printf("%s", str);]

    0 讨论(0)
  • 2021-01-05 06:17

    You need to compare str[i]'s value with the terminating '\0' of a string, rather than NULL, which is considered a pointer. Your

    while (str[i] != NULL ) {

    changed to

    while (str[i] != '\0') {

    below:

    int i = 0;
    char str[50] = {'s', 'a', 'm', 'p','l','e'}; //only for test
    while (str[i] != '\0') {
        putchar(str[i]);
        i++;
    }
    
    0 讨论(0)
提交回复
热议问题