如何修复此错误错误"error C2440: '=' : cannot convert from 'int (*)[]' to 'int *' "?

How do I fix this error error"error C2440: '=' : cannot convert from 'int (*)[]' to 'int *' "?

本文关键字:int 错误 to error 何修复 C2440 convert cannot from      更新时间:2023-10-16

这与类似的问题不同,因为我正在设置指向地址的指针值,而不是尝试分配不兼容的类型...我认为。

template <class Type>
class ArrayStack
{
private:
    int sz; // stack size
    int asz; // array size (implementation)
    Type* start; // address of first element
    Type arr[]; // Might need to intialize each element to 0!?
public:
    ArrayStack() { sz = 0; arr[0] = 0; asz = 0; start = &arr; }
/* other code... */
};

start = arr;应该可以解决问题。

  • 您可以将数组分配给指针,并将指针设置为数组的开头。

此外,空数组规范:

Type arr[]; 

不知道这意味着什么。可能与:

Type arr[0]; 

更正常:

Type arr[asz]; 

当然,数组大小需要是一个常量。

建议使用 std::vector<Type> arr 而不是 Type arr[]

template <class Type>
class ArrayStack
{
private:
    int sz; // stack size
    int asz; // array size (implementation)
    // Type* start; // address of first element
    // Don't need this at all.
    // You can use &arr[0] any time you need a pointer to the
    // first element.
    std::vector<Type> arr;
public:
    // Simplified constructor.
    ArrayStack() : sz(0), asz(0), arr(1, 0) {}
/* other code... */
};