Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison between pointer and integer in C

Tags:

c

pointers

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 write each char on the screen.

My code:

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

Can you help me please? I didn't find any usefull answer on the internet.

like image 889
user1313386 Avatar asked Apr 19 '12 07:04

user1313386


2 Answers

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.

like image 187
flolo Avatar answered Nov 11 '22 00:11

flolo


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);]

like image 9
Jerry Coffin Avatar answered Nov 11 '22 01:11

Jerry Coffin