質問

I have a question:

Why does this throw an error (cannot convert from int* to int[5])

int static_Array[5]; 
int *dynamic_Array;

dynamic_Array = new int[5];
static_Array = dynamic_Array;

while this works fine?

int static_Array[5]; 
int *dynamic_Array;

dynamic_Array = new int[5];
dynamic_Array = static_Array; //This line changed

I am guessing that types int can be converted to int* by the compiler? But then why couldn't int be converted to int* by the compiler as well?

Anyone can provide an actual explanation?

Thanks!

役に立ちましたか?

解決 2

This one:

int static_Array[5]; 
int *dynamic_Array = new int[5]; // 1.

dynamic_Array = static_Array;    // 2.
  1. dynamically allocates an array and stores the address of first element in pointer dynamic_Array
  2. overwrites this address with an address of the first element of the static_Array

But this one:

int static_Array[5]; 
int *dynamic_Array = new int[5];

static_Array = dynamic_Array;

attempts to initialize an array using an address (thus compiler gives error about invalid pointer to array conversion).

So why the first one works?
Because static array (on the right side) immediately decays to a pointer. This can not work the other way, there is no guarantee that this pointer points to an array.

他のヒント

When a raw array is specified in a context where a pointer is expected, it converts to pointer to first item (in the sense of producing that pointer value), which is called a type decay.

Contexts where that doesn't happen include sizeof expression, typeid expression and binding to reference to array.

But essentially that means that raw arrays are not assignable, and of course you cannot assign a pointer to an array variable, for what should the result be.

However, if you put an array in a struct, then you can assign the struct. And that's what std::array is. But when you want an assignable dynamic size array, use std::vector.

In passing, there is is also a similar type decay for functions.

int static_Array[5]; 

Here static_Array is const pointer to static_Array[0], you cannot modify it like,

 static_Array = dynamic_Array;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top