Why is the size of an array inconsisten depending on its location in the source code?

StackOverflow https://stackoverflow.com/questions/22359940

  •  13-06-2023
  •  | 
  •  

سؤال

I can declare animal_array1 and animal_array2. First one on the stack, while the second one is ... well, still on the stack but this time declared as a function parameter. Here is a sample code:

 #include <iostream>

 using namespace std;

 struct Animal
 {
 };

 void test(Animal animal_array2[10])
 {
     Animal animal_array1[10];
     if(sizeof(animal_array2) == sizeof(animal_array1))
         cout << "Both sizes are equal. That's expected!" << endl;
     else
         cout << "Mhhh sizes are *NOT* equal. That wasn't expected at all!" << endl;

 }

 int main()
 {
     Animal unused_var[10];
     test(unused_var);
 }

The output is:

 $./a.out 
 Mhhh sizes are *NOT* equal. That wasn't expected at all!

How can it be? Gcc bug? Or is it standard behavior? How can we get such streched results from the same apparent type?

هل كانت مفيدة؟

المحلول

Arrays are the only data types in C and C++ that cannot be passed by value. So an array decays to a pointer to the first element of the array (when declared and passed) as a function parameter.

So basically this:

void test(Animal animal_array2[10])

is actually:

void test(Animal *animal_array2)

but only as function parameter

and the array passed as a parameter:

test(unused_var);

decays to a pointer to the first elem in the array:

test(&(unused_var[0]));

(as a sidenote: but without the actual dereferencing)

نصائح أخرى

Arrays will decay into pointers when passed to a function in C++. Typically what you do is pass the known size to the function, as a separate parameter. Not in the between the square brackets.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top