David Hancock David Hancock - 1 year ago 149
C Question

Can't define char in C

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


#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]'
char hash = "#";
^ ~~~
1 error generated.
make: *** [mario] Error 1

usr usr
Answer Source

"#" 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 = '#';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download