Question

I have a function which prints the position of \r. Here's my code:

char buf[30];
strncpy(buf, "Hello world!\r\n", sizeof(buf));
int i;
char newline = "\r";

for (i = 0; i <= 13; i++){
    printf("buf[%d] = %c\n", i, buf[i]);
    if (buf[i] == newline){ 
        printf("i = %d\n", i);
    }
}

I tried to run it, but I get this error.

warning: incompatible pointer to integer conversion
  initializing 'char' with an expression of type 'char [2]'
  [-Wint-conversion]
char newline = "\r";

How would I come about fixing this, but without having to use any string functions?

Help much appreciated. Thanks!

Was it helpful?

Solution

buf[i] will be a character and you are comparing it with "\r", double quote in C indicates string not character. So you are comparing char with string. use newline as,

char newline='\r'

OTHER TIPS

here is the problem

char newline = "\r";  // "\r" is a string

It should be

char newline = '\r';

Notice in C, a char has to be surrounded with '', a string or char arrays have to be surrounded with "". (In python they are the same)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top