David Hancock David Hancock - 2 months ago 16
C Question

Can't define char in C

Sorry guys, new to C. Why can't I define a string (

char
)
"#"
?

#include <cs50.h>
#include <stdio.h>

int main(void)
{
int h = 10;
for (int i=0; i<=h; i++)
{
char hash = "#";
printf("%d", hash);
//printf("%d\n", hash*i);
}
}


Throws this error

~/workspace/pset1/ $ make mario
clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wshadow mario.c -lcs50 -lm -o mario
mario.c:24:14: error: incompatible pointer to integer conversion initializing 'char' with an expression of type 'char [2]'
[-Werror,-Wint-conversion]
char hash = "#";
^ ~~~
1 error generated.
make: *** [mario] Error 1

usr usr
Answer

"#" is a string literal (an array of 2 chars, consists of '#' and '\0'). If you want to initialize with a character literal then do:

char hash = '#';
Comments