无法从'诠释*'到'INT []'转换? [英] Cannot convert from 'int *' to 'int []'?

查看:103
本文介绍了无法从'诠释*'到'INT []'转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这可能是一个共同的问题,但我试图寻找,但仍然无法找到一个明确的答案。

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

我有以下的code:

int* f() {
    int a[] = {1,2,3};
    return a;
}

int main() {

    int a[] = f(); // Error here

    getch();
    return 0;
}

这code产生错误信息:无法从'诠释*'转换为'廉政[]

This code produces the error message: "Cannot convert from 'int *' to 'int []'"

我发现这很奇怪,因为我已阅读,指针和数组是相似的。例如,我们可以使用[I],而不是*(A + I)。
谁能给我解释清楚吗?

I found this quite strange because I have read that pointer and array are similar. For example, we can use a[i] instead of *(a + i). Can anyone give me a clear explanation, please?

推荐答案

有实际上在这个code两个错误。

There are actually two errors in this code.

首先,你是返回一个临时的地址(f 的int数组中的),因此它的内容在函数返回之后不确定的。任何企图通过返回的指针访问指向的内存将导致不确定的行为。

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.

其次,有来自++指针C中没有隐式转换到数组类型。它们是相似的,但不完全相同。数组可以衰变为指针,但它不工作的另一种方式圆如信息丢失在路上 - 一个指针刚刚重新presents一个内存地址,而一个阵列重新presents连续区域的地址通常与一个特定的大小。你也不能分配给数组。

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.

例如,我们可以使用[I],而不是*(A + I)

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.

这篇关于无法从'诠释*'到'INT []'转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆