Comparison between pointer and integer in C

后端 未结 8 1307
盖世英雄少女心
盖世英雄少女心 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:29

    NULL is a pointer and str[i] is the i-th char of the str array. char is and integer type, and as you compare them you get the warning.

    I guess you want to check for end of string, that would you do with a check for the char with the value 0 (end of string), that is '\0'.

    BUT: this wont help you as you define it just as and array of chars and not as a string, and you didnt define the termininating 0 in the char array (you get just lucky that it is implicit there).

    PS: Next time you should give at least the information where the compiler is complaining.

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

    The biggest problem with that code is that, depending on your implementation, it might compile without error.

    The problem, as others have said, is that NULL is intended to represent a null pointer value, not a null character value. Use '\0' to denote a null character. (Or you can use 0, which is equivalent, but '\0' expresses the intent more clearly.)

    NULL is a macro that expands to an implementation-defined null pointer constant. A null pointer constant can be either an integer constant expression with the value 0, or such an expression cast to void*. Which means that NULL may be defined either as 0 or as ((void*)0) (among other variations).

    Apparently your implementation defines it as something like ((void*)0), which is why you got the warning message. (It could, and IMHO should, have been treated as a fatal error).

    So never try to use NULL other than as a null pointer constant -- and don't count on the compiler to warn you if you misuse it.

    0 讨论(0)
提交回复
热议问题