c++ - 指针可以在函数调用期间转换为数组吗?

标签 c++ arrays pointers type-conversion

考虑以下代码:

#include <iostream>
#include <typeinfo>

void use_pointer(int *ptr)
{
    std::cout << typeid(ptr).name() << std::endl;
}

void use_array(int arr[])
{
    std::cout << typeid(arr).name() << std::endl;
}

int main()
{
    int *ptr = nullptr;
    // std::cout << typeid(int *).name() << std::endl; // output: Pi
    int arr[1];
    // std::cout << typeid(int[]).name() << std::endl; // output: A_i

    use_pointer(arr);
    use_array(ptr);
}

使用 g++ 6.5.0 输出编译这个程序:

$ g++ -std=c++11 arrays_2.cpp -Wall
$ ./a.out

Pi
Pi

现在,当调用 use_pointer(arr)array is being decayed到一个指针。 (这样说对吗?“衰变”这个词对我来说是个新词。)

C++ 标准在 [conv.array#1] :

An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The temporary materialization conversion ([conv.rval]) is applied. The result is a pointer to the first element of the array.

我想我明白我的“int 数组”转换为“指向 int 的指针”。 (对吗?)

现在,调用 use_array(ptr) 时到底发生了什么。由于本例中的参数类型是 int 数组,“指向 int 的指针” 是否转换为 “int 数组”

非常感谢指向该标准的指针。

最佳答案

指针是指针,数组是数组。然而,数组自然退化为指向其第一个元素的指针。因此,当您将数组 arr 传递给您拥有的任何函数时,它将衰减为 &arr[0]

另请注意,在声明函数参数时,数组符号(如 int arr[])并不意味着它是一个数组,编译器仍将其转换为指针(即 int* arr).

关于从数组到指针的衰减,它不可能以相反的方式发生。一旦你有了一个指针,你所拥有的就是那个指针和它指向的单个元素。

关于c++ - 指针可以在函数调用期间转换为数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53363246/

相关文章:

c++ - const 在运行时有影响吗

c++ - 免费的基于 C/C++ 的 zip/zip64 库?

php - 从数组中对数据库进行排序

javascript - Javascript 中的数组到对象

c++ - main() 内外的字符指针声明

c - (const char *str) , (char const *str) 和 (char *const str) 之间有什么区别?

c++ - 以 FLOPS 估算 GPU 的效率(CUDA SAMPLES)

c++ - 为什么字符串 operator= 上的 double free?

javascript - 在 JavaScript 中复制任意 n 维数组?

c - 将 char 数组传递给函数