I want to use the length of my array as part of the control for my for loop but I can't. Why is this? What can I do to make it loop as many times as there are indices in the array?
edit: After thinking about it some more I figured that since when arrays are passed into functions, the only thing actually passed is a pointer to the first element so that provides access to the array but not the entire array, right? Would I have to sort of "re-create" my array's structure inside this function?
use sizeof here to determine the size of array and pass the base address of array ... basically the name of variable which always store the address of array.
so your code will become as follows:
Hmm...for some reason when I use this I get 4 instead of 10. My array has 10 elements and I can even see them inside my watch window but I do the following:
An array is just a pointer to a block of data, so sizeof will always return 4 (unless it is specifically a static array, which may cause sizeof to give you the size of the entire block) and there is no length function. If you pass an array to a function, you also need to pass the size of the array as a second argument.
@bluecoder, that's the point. You are trying to get the size of an array from a pointer which is not possible so you get an error. Much better than compiling code that fail at runtime.
When you pass an array to a function by pointer there is no way to get its size. You must pass the size as a separate parameter.
1 2 3 4 5
void function( int array[] ) // 'array' is actually a pointer
{
int size = calcsize( array) ; // no way to get the size from just a pointer. Compiler error
cout<<"\n Size = "<<size;
}
The alternative would be to pass the array by reference, but this has some ugly syntax:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void function( int (&array)[10] )
{
int size = calcsize( array ); // now this will work, but of course it will always be 10
}
int main()
{
// this also means you can only pass arrays of 10 ints to the function. No more, no less
int array10[10];
function( array10 ); // OK
int array11[11];
function( array11 ); // ERROR, int[11] is not int[10]
int* ptr = newint[10];
function( ptr ); // ERROR, int* is not int[10]
}
So yeah -- the best solution here is what's already been said: pass the size as a paramter.
Another useful approach is to write functions in terms of iterators. Then it doesn't matter if it's a C array or a C++ array or a vector, as long as begin() and end() are passed.
HI
@ Disch and @Peter87 if we need to pass the size of the vector to the function then , i am not able to understand about , as to why
we cannot use the approch of
The problem is that when an array is passed to a function it is passed as a pointer, so the compiler has no information about its size inside the function. So taking sizeof(array) inside the function only returns the size of the pointer to the array, not the amount of memory allocated.