tags:

views:

90

answers:

3

I'm doing C programming and need help with this problem..

char str[] = "Hello";
char * ptr = str;
char ** ptr2 = (char**)ptr;

I have these three lines in a header file. The first two lines are fine but an error will occur in the third line. Explicitly the error is "initializer element is not constant".

Is there any other way of assigning the address of ptr to *ptr2 globally? Or is this impossible to achieve globally? I want this done so ptr2 can be the common access point but what it's pointing to can be changed if necessary.

+8  A: 

First of all, this:

char ** ptr2 = (char**)ptr;

Doesn't assign the address of ptr to ptr2. It assigns the address of str (contained in ptr) to ptr2 and pretends its a char** instead of a char*, with possibly disastrous results later when you try to use it. You probably meant:

char ** ptr2 = &ptr;

Since &ptr (the address) is indeed constant, unlike ptr (the value), this should compile without error. Plus, it's what you really want anyway.

Tyler McHenry
+1  A: 

char str[] is a pointer to the first element in an array of chars called str - in other words it is a pointer-to-char.

char * ptr is a pointer-to-char as well, so char * ptr = str is fine.

char ** ptr2 is a pointer-to-pointer-to-char, though, so ptr2 = ptr doesn't make any sense - you have an extra layer of pointing that you don't want. You want

char ** ptr2 = &ptr;

which will extract the address of ptr, correctly giving a pointer-to-pointer-to-char.

Spencer Nelson
`char str[]` is an incomplete array declaration that becomes complete when initialised with a string literal. Even after initialisation, it is still not a pointer.
dreamlax
@dreamlax Yes it is, they are interchangable notations. From Kernighan and Ritchie, page 99:"Rather more surprising, at least at first sight, is the fact that a reference to a[i] can also be written *(a+i). In evaluating a[i], C converts it to *(a+i) immediately; the two forms are equivalent [...] As the other side of this coin, if pa is a pointer, expressions may use it with a subscript; pa[i] is identical to *(pa+i).
Spencer Nelson
Just because an array can be used like a pointer, it does not make it a pointer. Consider the difference between `sizeof(str)` and `sizeof(ptr)`. If `str` and `ptr` are both pointers to `char`, then they should have equal size, but they don't have equal size (unless for example, `str` is a string containing four characters and pointers are 32-bit).
dreamlax
A: 

My guess is you want ptr2 to point to ptr. This means assigning the address of ptr to ptr2, not to *ptr2 You have to do it like this:

char** ptr2 = &ptr;

I don't understand your goal. ptr can be changed as necessary too.

Please consider better names for your variables.

Maciej Hehl
I think the names of the variables have been masqueraded since the original variable names are probably irrelevant.
dreamlax
Thanks guys for such quick answers! It fixed the error :)
ilikeC