1

What, exactly, is a (*) and how do you cast it?

"error C2440: '=' : cannot convert from 'char *[]' to 'char (*)[]'"  

Trying to get a SmartPointer to take array values. Header:

template <typename T> class SmartPointer
{
private:
    T* myPtr;
    int* count;

public:
    T* Value();

    SmartPointer(const SmartPointer<T>& a)
    {
        myPtr = a.myPtr;
        count = a.count;
        ++*count;
    }
SmartPointer(T* ptr);
SmartPointer(T value) { myPtr = &value; count = new Int(); ++*count; }
~SmartPointer();


void operator =(T a);
operator T*();
    T* operator ->();
};

Relevant calling line:

SmartPointer<char[]> str = SmartPointer<char[]>(new char[20]);
Narf the Mouse
  • 1,541
  • 5
  • 18
  • 30
  • 1
    possible duplicate of [C pointer to array/array of pointers disambiguation](http://stackoverflow.com/questions/859634/c-pointer-to-array-array-of-pointers-disambiguation) – user541686 Feb 17 '11 at 07:50
  • 1
    Your value constructor (`SmartPointer(T value)`) is doing something very bad - storing a pointer to the constructor argument, which will be destroyed with the constructor exits. You probably want to initialise it as `myPtr(new T(value))`, assuming the destructor is going to `delete` it when the count reaches zero. Although then you have exception-safety issues; personally, I wouldn't provide that constructor at all, and leave it to the calling code to clone objects when necessary. – Mike Seymour Feb 17 '11 at 07:55

3 Answers3

3

A char*[] is array of char*, while a char(*)[] is a pointer to an array of char.

See this question for more info.

Community
  • 1
  • 1
user541686
  • 205,094
  • 128
  • 528
  • 886
3

I'm not familiar with this class but I would think you want:

SmartPointer<char> str = SmartPointer<char>(new char[20]);

Or possibly:

SmartPointer<char> str = new char[20];
Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • Thanks, it successfully creates the SmartPointer. Or, possibly almost successfully. That is to say, I now get a heap corruption error before the SmartPointer gets to deallocate...Ah, "Invalid Address specified to RtlFreeHeap( 00390000, 0040211C )". – Narf the Mouse Feb 17 '11 at 07:57
  • So, yeah, thanks, and if I could upvote your answer, I would. – Narf the Mouse Feb 17 '11 at 08:00
  • @Narf I see I misinterpreted your code at my first look at it. Now I'm not clear on exactly how you changed your code. Are you using your original copy constructor as it appears to be flawed. (When finished, both the source and target instance would refer to the same memory.) At any rate, it should be a simple matter to step through with the debugger to see if you can see what's happening. – Jonathan Wood Feb 17 '11 at 08:04
0

In the general case, you can use a program called cdecl (available on the web) to tell you, or use these fun rules to decode types yourself.

Community
  • 1
  • 1
j_random_hacker
  • 50,331
  • 10
  • 105
  • 169