Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C double character pointer declaration and initialization

I always though that declaring

char *c = "line"; 

was the same as

char c[] = "line"; 

and so I did

char **choices = { "New Game", "Continue Game", "Exit" }; 

Which gives me an incompatible pointer type, where

char *choices[] = { "New Game", "Continue Game", "Exit" }; 

doesn't. Any help on understanding this?

like image 253
vascop Avatar asked Jan 28 '11 19:01

vascop


People also ask

How pointers are declared and initialized in C?

While declaring/initializing the pointer variable, * indicates that the variable is a pointer. The address of any variable is given by preceding the variable name with Ampersand & . The pointer variable stores the address of a variable. The declaration int *a doesn't mean that a is going to contain an integer value.

What is a double char pointer in C?

The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double pointers.

What is a double char pointer?

A double-pointer is a pointer to a pointer. For instance, a char pointer to pointer is declared as char** ptrptr .


1 Answers

char *c = "line"; 

is not the same as

char c[] = "line"; 

it's really the same as

static const char hidden_C0[] = "line"; char *c = (char *)hidden_C0; 

except that the variable hidden_C0 is not directly accessible. But you'll see it if you dump out generated assembly language (it will usually have a name that isn't a valid C identifier, like .LC0). And in your array-of-string-constants example, the same thing is going on:

char *choices[] = { "New Game", "Continue Game", "Exit" }; 

becomes

const char hidden_C0[] = "New Game"; const char hidden_C1[] = "Continue Game"; const char hidden_C2[] = "Exit";  char *choices[] = { (char *)hidden_C0, (char *)hidden_C1, (char *)hidden_C2 }; 

Now, this is a special case behavior that is available only for string constants. You cannot write

int *numbers = { 1, 2, 3 }; 

you must write

int numbers[] = { 1, 2, 3 }; 

and that's why you can't write

char **choices = { "a", "b", "c" }; 

either.

(Your confusion is a special case of the common misconception that arrays are "the same as" pointers in C. They are not. Arrays are arrays. Variables with array types suffer type decay to a pointer type when they are used (in almost every context), but not when they are defined.)

like image 100
zwol Avatar answered Oct 02 '22 08:10

zwol