1

I'm new with C++ and came to this problem, here is my code:

shared_ptr<char[]>var(new char[20]);

char *varptr = *(var.get());

So I'm creating smart pointer of char array.

The problem that I'm having is that during compilation it gives me error saying:

cannot convert argument 1 from 'char *' to 'char(*)[]'

As the declaration of shared_ptr::get says T* get() const noexcept; it returns the pointer of template, in my case pointer to char[]. Dereferencing it should give me the char[] and assigning it to char* should be ok.

It seems like I'm missing something and can't figure out what.

What is the difference between char* and char(*)[]? Isn't char(*)[] just a pointer of char array? Shouldn't assigning it to char* be ok?

Ojs
  • 924
  • 1
  • 12
  • 26

1 Answers1

2

char(*)[] is a pointer to an array (of unknown size) of char, it can point to an array.

char* is a pointer to a char, it can point to an element of an array.

Semantically the two types are very different things.

To get a char * from a char(*)[], you need to get a pointer to an specific element of the array (typically the first element):

char* varptr = &(*var.get())[0];

And if all you want is a string, then use std::string instead.


To explain the difference between pointer to element, and pointer to array, consider the following array:

char a[3];

A pointer to the first element (a[0]) can be expressed as &a[0], which is what plain a decays to. A pointer to the whole array is &a.

If we show it how it's laid out in memory, with some "pointers" added, it's like this:

+------+------+------+-----
| a[0] | a[1] | a[2] | ...
+------+------+------+-----
^      ^      ^      ^
|      |      |      |
a      a+1    a+2    |
|                    |
&a                   (&a)+1

Even through the pointers a (which is equal to &a[0]) and &a point to the same location, they are two different pointers and doing pointer arithmetic on them will do different things.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thanks. One more question please, pointer of char array and pointer to char aren't the same thing? they both hold the address of same type? why is it problem to assign one to another? sorry if question sounds silly. – Ojs Jun 09 '19 at 11:16
  • Correct me if I'm wrong, only reason why assigning pointer of char array to char pointer is impossible because of the arithmetic operation on them are different? – Ojs Jun 09 '19 at 11:24
  • @Ojs No the *types* are different. Pointer arithmetic difference is because of the type difference. – Some programmer dude Jun 09 '19 at 11:35
  • and one more please :) `char(*)[]` is of "type" `&a` right? – Ojs Jun 09 '19 at 12:00
  • @Ojs The type of `&a` (in my example) is really `char(*)[3]`. In your question the type is `char(*)[]` (with an indeterminate size) because the smart pointer doesn't know the size. – Some programmer dude Jun 09 '19 at 12:02
  • Thank you very much for brief explanations – Ojs Jun 09 '19 at 12:04