When a function has a specific-size array parameter, why is it replaced with a pointer?

前端 未结 3 1249
南笙
南笙 2020-11-21 05:43

Given the following program,

#include 

using namespace std;

void foo( char a[100] )
{
    cout << \"foo() \" << sizeof( a ) <         


        
3条回答
  •  心在旅途
    2020-11-21 06:02

    There is magnificent word in C/C++ terminology that is used for static arrays and function pointers - decay. Consider the following code:

    int intArray[] = {1, 3, 5, 7, 11}; // static array of 5 ints
    //...
    void f(int a[]) {
      // ...
    }
    // ...
    f(intArray); // only pointer to the first array element is passed
    int length = sizeof intArray/sizeof(int); // calculate intArray elements quantity (equals 5)
    int ptrToIntSize = sizeof(*intArray); // calculate int * size on your system
    

提交回复
热议问题