When a function has an array parameter of a certain size, why is it replaced with a pointer?

Given the following program,

#include <iostream> using namespace std; void foo( char a[100] ) { cout << "foo() " << sizeof( a ) << endl; } int main() { char bar[100] = { 0 }; cout << "main() " << sizeof( bar ) << endl; foo( bar ); return 0; } 

exits

 main() 100 foo() 4 
  • Why is the array passed as a pointer to the first element?
  • Is this a legacy from C?
  • What does the standard say?
  • Why is there strict security like C ++?
+56
c ++ arrays standards sizeof function-parameter
Aug 25 '09 at 13:17
source share
3 answers

Yes, it is inherited from C. Function:

 void foo ( char a[100] ); 

The parameter will be configured as a pointer, and it will be as follows:

 void foo ( char * a ); 

If you want to keep the type of the array, you must pass a reference to the array:

 void foo ( char (&a)[100] ); 

C ++ '03 8.3.5 / 3:

... The type of function is determined using the following rules. The type of each parameter is determined from its own decl-specifier-seq and declarator. After determining the type of each parameter, any parameter of the type "array T" or "returning function T" is configured as a "pointer to T" or "pointer to a return function T", respectively ....

To explain the syntax:

Check the correctness of the "right left" rule in google; I found one description here .

It will be applied to this example as follows:

 void foo (char (&a)[100]); 

Start with id 'a'

'a' is

Move to the right - we will find ) so that we look in the opposite direction ( . When we move to the left, we go through &

'a' is a link

After & we get to the opening ( so that we turn again and look right. Now we see [100]

'a' is a reference to an array of 100

And we again turn the direction until we reach char :

'a' - reference to an array of 100 characters

+62
Aug 25 '09 at 13:22
source share
โ€” -

Yes. In C and C ++, you cannot pass arrays to functions. It is as it is.

Why are you making simple arrays anyway? Have you looked at boost / std::tr1::array / std::array or std::vector ?

Please note that you can pass a reference to an array of arbitrary length to a function template. Above my head:

 template< std::size_t N > void f(char (&arr)[N]) { std::cout << sizeof(arr) << '\n'; } 
+11
Aug 25 '09 at 13:22
source share

In C / C ++ terminology, there is a great phrase 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 
+1
Dec 21 '11 at 4:53 on
source share



All Articles