Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pointers and array declaration

Tags:

c

pointers

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?

like image 385
user339946 Avatar asked Mar 08 '26 12:03

user339946


2 Answers

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

like image 196
AusCBloke Avatar answered Mar 10 '26 02:03

AusCBloke


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.

like image 34
cpx Avatar answered Mar 10 '26 02:03

cpx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!