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

MyFunc(&array[])

Recommended Answers

All 5 Replies

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.

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.

Please see previous post, was editing when you posted.

> 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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.