0

i am a newbie to c++, as i wrote program to test how to pass array as the parameters in function, i wrote this little program:


#include <iostream>
using namespace std;

void pass_by_array(int a[]) {
int a_len = sizeof(a);
int e_len = sizeof(a[0]);

cout << "size of array in func: " << a_len << endl;
cout << "size of element in func: " << e_len << endl;
}

int main() {
int foo[] = {1, 8, 2, 7, 3, 6};

int a_len = sizeof(foo);
int e_len = sizeof(foo[0]);

cout << "size of array in main: " << a_len << endl;
cout << "size of element in main: " << e_len << endl;

pass_by_array(foo);

return 0;
}

here's the result i got:

size of array in main: 24
size of element in main: 4
size of array in func: 8
size of element in func: 4

so what the hell is going on there? the size of the array changed?!

wusj
  • 1

2 Answers2

4

When you pass an array to a function, it decays into a pointer to its first element. Therefore sizeof(a) actually gives you the size of a pointer to int. On your machine, it appears that this is 8.

If you want to pass an array to a function such that the array still knows its size, use std::vector or std::array, not a plain C-style array.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
0

As per your program:

int a_len = sizeof(foo);
int e_len = sizeof(foo[0]);

is a function variable so compiler can interpret it as an array because it is on same stack frame of the function where it is declared and initialized.

For your program: main()

And when you pass an array to another function

pass_by_array(foo);

it is converted as a pointer which is been defined in the stack frame of the receiving function and stores the address of the array.

So because of that as per your program:

int a_len = sizeof(a);
int e_len = sizeof(a[0]); 

first statement will give you the size of int* a i.e. sizeof (pointer) or int as per the compiler. As pointers can be used as an array a[0] it will give you the sizeof(int)

Hope this will help you to understand.

A B
  • 1,461
  • 2
  • 19
  • 54