Search code examples
cpointers

Comparison between a pointer and an integer in C


I want to write each char on the screen:

int i = 0;
char str[50] = {'s', 'a', 'm', 'p','l','e'}; //only for test
while (str[i] != NULL) {
    putchar(str[i]);
    i++;
}

But my compiler says:

warning: comparison between pointer and integer.

Why?


Solution

  • NULL is a pointer, and str[i] is the i-th char of the str array. char is an 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 won't help you as you define it just as an array of chars and not as a string, and you didn't define the terminating 0 in the char array (you get just lucky that it is implicit there).