I’m confused by this snippet from the book I’m reading. Text strings are put into a char array. There are four words, with four elements in the array. Wait, but that means a single char element is containing a whole text string. I’m certain chars can only handle a single character. Here’s the code.
const char *words[4] = { "aardvark", "abacus",
"allude", "zygote" };
So what gives? How can the author be using chars to store whole strings? I know the solution must be blindingly obvious, but I just can’t see it. Also, what’s with the const keyword? Why would it need to be read only if all we plan to do with this array is count the length of each word using strlen()?
The code does not use chars to store strings, note that the declaration is an array of
char *.A
charcan hold a single character, and achar *can be used to point to the first element of an array of characters, which can hold a standard C string. This is an important C fundamental: see achar *and you should immediately think of null-terminated C strings.Similarly, an
int *can be used to refer to an entire array ofint, by holding the address of the firstintin the array.int*can be subscripted the same as an array declared using[].A
char *can also be used to simply hold the address of a single character – i.e. not the first character in a null terminated string.