views:

146

answers:

7

I am just trying to get my head around various pointer concepts and I have the following code:

char** a = new char*; // assign first pointer to point to a char pointer

    char b[10] = "bla bla";
    *a = new char; //assign second pointer a block of memory.  -> This looks wrong to me!!  
    (**a) = b[2]; 

So what is wrong with the second 'pointer' memory allocation? It runs and stuff, but it just feels wrong.

EDIT:

Thanks for clarifying this! I learnt something!

+1  A: 

There is nothing wrong with it, except that using dynamic memory allocation that much is rather bad style in C++.

Tronic
so how would you do it in good C++ style then?
Tony
char a = 'a'; ... or if one needs a double pointer for some obscure reason, char a = 'a'; char* ap = char** app =
Tronic
+1  A: 

*a = new char; means that you create a single char variable using its default constructor. It's equivalent to *a = new char(); And you assign the address of the just created variable to the pointer a

anthares
A: 

Nothing wrong here :)

drlazy
+1  A: 
char** a = new char*;  // a is a pointer to a pointer to a type char. allocate a new pointer variable and make a point to it.
char b[10] = "bla bla"; // define a char array.
*a = new char; // allocate a new char and make the pointer whose address is in a point to it.
(**a) = b[2]; // copy the 3rd char of b to the char whose address is pointed by a.
codaddict
A: 

The only reason it's "wrong" is that it's unclear. You obviously agree that it's unclear.

In some contexts, similar code may be "right" when with better names and better class structure the goal is clear, removing doubt about the means as well.

MSalters
A: 

There's nothing technically wrong with it.

However, it is uncommon to explicitly allocate a pointer to a pointer to a single element on the same page of code. You wouldn't do this in practice very often, for the same reason that you would rarely say "If you need to know about the FooBar, ask Tom, and Tom is me."

Jesse Millikan
A: 

nothing wrong, techically. But it seems the style is rarely used.

Foxcat