I just self-taught myself C++. I've got all the basics down, but I'm still working out some of the nuances.

Basically, I'm passing an array into a function, and I need the function to be able to pass the length of the array to an integer. I'm using

int len = sizeof(array)/sizeof(array[0])

When I use this code in the main function, it works just fine, assigning the length of the array to len. However, when I pass the array as an argument to a function, and then run the code inside the function, it always evaluates sizeof(array) as 4 bytes, instead of 4 bytes * array length. So my int always ends up being assigned 1.

Is there a way to figure out the length of an array thats been passed to a function? Or am I just stuck passing the length as an additional argument?

I tried passing the array by reference, but I got a compiler error saying I can't have an array of references in my function declaration. Can I change the syntax so the compiler identifies it as a reference to an array, instead of an array of references? And would that even solve my length problem?

The syntax I'm using is for my function declaration/definition is

7 Years
Discussion Span
Last Post by tokomonster

Arrays are already passed by reference by default. There is nothing you need to do to accomplish this.

An array is nothing more than a pointer to the address of the first element in the array. When you access an element, you offset from the address of the first element by a specified increment then read the value stored in that location. As a result, I suspect what you are actually getting from sizeof() is the size of the pointer used as the identifier within the local scope of your function. You'll probably have to pass the length as a separate argument.

Edited by Fbody: n/a


Arrays are nothing more than pointers. They are already passed by reference. There is nothing you need to do.

Ok. That explains why I can't have a reference to an array. I still need the function to figure out the length of the array.

I should probably clarify, it is not the function's sole purpose to figure out the length of the array. I just need the length of the array for some other calculations in the function.

Edited by tokomonster: n/a


> I still need the function to figure out the length of the array.
Pass the length as another parameter.

Or, consider the alternatives that std::vector offers.

The sizeof thing you posted only works when the actual array definition is in scope. As soon as you call a function, you're just left with a pointer.


Thanks guys. I'll have to look into std::vector. The book I read didn't cover it.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.