Cannot convert from 'int *' to 'int []'?

后端 未结 1 570
南旧
南旧 2021-02-15 03:18

I know this might be a common question but I have tried to search but still cannot find a clear answer.

I have the following code:

int* f() {
    int a[]         


        
1条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-15 03:21

    There are actually two errors in this code.

    Firstly, you are returning the address of a temporary (the int array within f), so its contents are undefined after the function returns. Any attempt to access the memory pointed to by the returned pointer will cause undefined behaviour.

    Secondly, there is no implicit conversion from pointers to array types in C++. They are similar, but not identical. Arrays can decay to pointers, but it doesn't work the other way round as information is lost on the way - a pointer just represents a memory address, while an array represents the address of a continuous region, typically with a particular size. Also you can't assign to arrays.

    For example, we can use a[i] instead of *(a + i)

    This, however, has little to do with the differences between arrays and pointers, it's just a syntactic rule for pointer types. As arrays decay to pointers, it works for arrays as well.

    0 讨论(0)
提交回复
热议问题