jlHe233 2022-03-15 00:21 采纳率: 88.6%
浏览 14
已结题

带入function array size输出为何不同


#include <iostream>
using namespace std;


void sort(int a[])
{
    int b=sizeof(a)/sizeof(a[0]);
    cout<<b<<endl;
}

int main(){
    int a[100]={1,4,2,4,5,2,3};
    int b=sizeof(a)/sizeof(a[0]);
    cout<<b<<endl;
    sort(a);
}

为什么输出array size是100 2,而不是两个100

  • 写回答

3条回答 默认 最新

  • _GX_ 2022-03-15 06:06
    关注

    如果一个函数参数是数组类型,该参数类型自动转换为相应的指针类型。即

    void sort(int a[]);
    void sort(int a[100]);
    

    自动转换为

    void sort(int *a);
    

    数组大小的信息丢失,因为你需要额外用一个参数来传递数组大小

    void sort(int a[], int size);
    

    但是如果参数是数组引用类型,那么该参数类型的数组大小信息是被保留的。

    void sort(int (&a)[100])
    {
        cout << sizeof(a) / sizeof(int) << endl; // 输出100
    }
    

    https://en.cppreference.com/w/c/language/array#Array_to_pointer_conversion

    When an array type is used in a function parameter list, it is transformed to the corresponding pointer type: int f(int a[2]) and int f(int* a) declare the same function. Since the function's actual parameter type is pointer type, a function call with an array argument performs array-to-pointer conversion; the size of the argument array is not available to the called function and must be passed explicitly:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 3月23日
  • 已采纳回答 3月15日
  • 创建了问题 3月15日

悬赏问题

  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效