1

I need the use the length of a passed array 'X' in a function. The array is created in the main function. I print out the following from the main function:

std::cout << "\n" << sizeof(X);

which yields: 400

The array 'X' is then passed to a function where the length of X is needed. I print out the following from the function:

std::cout << "\n" << sizeof(X);

which yields: 8

I am expecting 400, as my array has 100 float elements. Why does sizeof() not return the same size as when it was called in the main function? (I assure you that there are actually 100 elements in array X because the rest of the program works.)

Thanks for any help!

jasper
  • 193
  • 3
  • 17

3 Answers3

4

When you pass a raw array (e.g. declared as int arr[100];) as a parameter to some other function, is it decayed into a pointer (whose size is often 8 on 64 bits processor).

So you declare your array

int arr[100];

then you declare your function

void f(int arr[]);

which is understood as

void (int *arr);

In C++11 you could use std::array so declare

std::array<int,100> arr;

and pass preferably a reference to it:

void f(std::array<int,100> &arr);

(you could pass it by value, but then all the 100 integers would be copied on function invocation).

BTW, consider also std::vector, and take many hours to read a good C++ programming book.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • is there any way to find the length if the array other than passing the length to the function or using std::array ? – jasper Nov 10 '13 at 17:16
  • No, there is no such way; however you could pass some object (i.e. some instance of some `class` or `struct` ...), and that object would carry the size of the array. Consider also using [std::vector](http://www.cplusplus.com/reference/vector/) – Basile Starynkevitch Nov 10 '13 at 17:18
  • Yes, there is a way. You can pass the array by reference, as indicated in Etherealone's answer. – Benjamin Lindley Nov 10 '13 at 17:20
2

C arrays can be implicitly reduced to pointers and they will be. For sizeof to work correctly you would need to do the following:

template<size_t N>
void func(char (&arr)[N])
{
/* sizeof(arr) == N in this scope */
}

or you could use C++11 std::array.

Etherealone
  • 3,488
  • 2
  • 37
  • 56
  • 1
    It does need to be a reference. Declaring the parameter as `char arr[N]` is equivalent to declaring it as `char * arr`, losing the size. Built-in arrays can't be passed by value without wrapping them in a class. – Mike Seymour Nov 10 '13 at 18:12
  • @MikeSeymour Tested it and indeed you are right. But it doesn't even compile if it is not a reference. – Etherealone Nov 10 '13 at 18:17
1

In main the array size will be 4*100 = 400, but when you pass the address of array to another function it is now a pointer pointing to array, meaning the size of X is now size of pointer in called function.

Sunil Bojanapally
  • 12,528
  • 4
  • 33
  • 46