user339946
user339946

Reputation: 6119

C pointers and array declaration

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

Answers (5)

AusCBloke
AusCBloke

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 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[].

Upvotes: 5

Robert Peters
Robert Peters

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

cpx
cpx

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

AndersK
AndersK

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

duedl0r
duedl0r

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

Related Questions