Reputation: 63200
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!
Upvotes: 1
Views: 1201
Reputation: 51
nothing wrong, techically. But it seems the style is rarely used.
Upvotes: 0
Reputation: 3145
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."
Upvotes: 0
Reputation: 11223
*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
Upvotes: 1
Reputation: 179907
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.
Upvotes: 1
Reputation: 455122
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.
Upvotes: 2
Reputation: 10430
There is nothing wrong with it, except that using dynamic memory allocation that much is rather bad style in C++.
Upvotes: 2