I'm currently learning C through "Learning C the Hard Way"
I am a bit confused in some sample code as to why some arrays must be initialized with a pointer.
int ages[] = {23, 43, 12, 89, 2};
char *names[] = {
"Alan", "Frank",
"Mary", "John", "Lisa"
};
In the above example, why does the names[] array require a pointer when declared? How do you know when to use a pointer when creating an array?
A string literal such as "Alan" is of type char[5], and to point to the start of a string you use a char *. "Alan" itself is made up of:
{ 'A', 'L', 'A', 'N', '\0' }
As you can see it's made up of multiple chars. This char * points to the start of the string, the letter 'A'.
Since you want an array of these strings, you then add [] to your declaration, so it becomes: char *names[].
Prefer const pointers when you use string literals.
const char *names[] = {
"Alan", "Frank",
"Mary", "John", "Lisa"
};
In the declaration, name is a array of const char pointers which means it holds 5 char* to cstrings. when you want to use a pointer, you use a pointer, as simple as that.
Example:
const char *c = "Hello world";
So, when you use them in an array, you're creating 5 const char* pointers which point to string literals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With