Reputation: 6119
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?
Upvotes: 2
Views: 661
Reputation: 18492
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 char
s. 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[]
.
Upvotes: 5
Reputation: 21
The use of "array of pointer" is not required.
The following will work as well. It's an array of 20 byte character arrays. The compiler only needs to know the size of the thing in the array, not the length of the array. What you end up with is an array with 5 elements of 20 bytes each with a name in each one.
#include <stdio.h>
char names[][20] = {
"Alan", "Frank",
"Mary", "John", "Lisa"
};
int main(int argc, char *argv[])
{
int idx;
for (idx = 0; idx < 5; idx++) {
printf("'%s'\n", names[idx]);
}
}
In your example the size of the thing in the array is "pointer to char". A string constant can be used to initialize either a "pointer to char" or an "array of char".
Upvotes: 2
Reputation: 17557
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.
Upvotes: 3
Reputation: 36082
In the case of char *names[]
you are declaring an array of string pointers.
a string in C e.g. "Alan"
is a series of characters in memory ended with a \0 value marking the end of the string
so with that declaration you are doing this
names[0] -> "Alan\0"
names[1] -> "Frank\0"
...
then you can use names[n] as the pointer to the string
printf( "%s:%d", names[0], strlen(names[0]) );
which gives output "Alan:4"
Upvotes: 2
Reputation: 9424
Because the content of the array is a char*
. The other example has an int
. "Alan" is a string, and in C you declare strings as char pointers
.
Upvotes: 2