bmnsn
bmnsn

Reputation: 17

Dereferencing an Array of Pointers

I'm having some trouble wrapping my head around this simple dereferencing statement.

I've tried printing **names, and then I get what I expect to get from *names -- 'C'. However, *names gives me 'D'.

#include <stdio.h>


int main(void)
{
   char *names[] = {"Carl", "David", "Gibson", "Long", "Paul"};
   printf("%c\n", *names);

   return 0;
}

The console prints out 'D'. I'm not sure why the resulting char from *names is not the first letter of the first item, 'C'.

Upvotes: 0

Views: 80

Answers (2)

Julio P.C.
Julio P.C.

Reputation: 330

When you compile this code, GCC will give you the following:

test.c:5:12: warning: format ‘%c’ expects argument of type ‘int’, but argument 2 has type ‘char *’ [-Wformat=]
   printf("%c\n", *names);
           ~^     ~~~~~~
           %s

So you're basically trying to print the first character of the first name, but instead of passing a char as an argument, your're passing a pointer to char. What you could do is this:

printf("%c\n", *names[0]);

in which you specify that you want the first character from the first element.

Also, using **names is the same as using *names[0]

Upvotes: 3

nullptr
nullptr

Reputation: 4474

This is undefined behavior and the output varies with the compiler.
When I run this with gcc, there is no output. Using **names prints 'C'.
The undefined behavior is because of the wrong format specifier. You use %c, but *names point to the first element in the array, ie a char array storing "Carl".
Use the %s format specifier to print strings.

printf("%c\n", *names);

Upvotes: 3

Related Questions