First, some basics:
In C, a string is a sequence of character values followed by a 0-valued terminator. Strings are stored in arrays of char
, not single char
objects.
A string literal is delimited by double quotes ("
), while character constants are delimited by single quotes ('
).
In your code
char casa = 'Esquina';
you declare casa
as a char
, meaning it can only store a single character value, not a string. You initialize it with 'Esquina'
, which is not a string literal, but a multibyte character constant. Multibyte character constants are mapped on to char
objects in an implementation-defined manner. In this particular case, it's not what you want.
casa
should be declared as either
const char *casa = "Esquina";
or
char casa[] = "Esquina";
depending on whether or not you will need to modify the contents of the string later on. The first version declares casa
as a pointer to the first character in the string literal "Esquina"
1. The second version declares casa
as a 8-element array of char
2 and copies the contents of the string literal to it, giving us
casa[0] == 'E'
casa[1] == 's'
casa[2] == 'q'
casa[3] == 'u'
casa[4] == 'i'
casa[5] == 'n'
casa[6] == 'a'
casa[7] == 0
To print it out, you'd use the %s
conversion specifier in printf
:
printf("Letra %c, numero %d, em uma %s\n", letra, numero, casa);
- String literals are stored as arrays of
char
such that the array is allocated when the program starts up and released when the program terminates. Attempting to modify the contents of a string literal invokes undefined behavior - it may work, it may cause a segfault, it may do something unexpected. To prevent us from accidentally modifying the string literal through casa
, we declare it as const char *
; this way, any attempt to change the string will cause the compiler to yak.
- The size is taken from the length of the string, plus an additional element to store the string terminator.