Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determine size of array if passed to function

Is it possible to determine the size of an array if it was passed to another function (size isn't passed)? The array is initialized like int array[] = { XXX } ..

I understand that it's not possible to do sizeof since it will return the size of the pointer .. Reason I ask is because I need to run a for loop inside the other function where the array is passed. I tried something like:

for( int i = 0; array[i] != NULL; i++) { ........ } 

But I noticed that at the near end of the array, array[i] sometimes contain garbage values like 758433 which is not a value specified in the initialization of the array..

like image 851
Charles Khunt Avatar asked Jun 09 '09 03:06

Charles Khunt


People also ask

How do you get the size of an array passed to a function?

The reason is, arrays are always passed pointers in functions, i.e., findSize(int arr[]) and findSize(int *arr) mean exactly same thing. Therefore the cout statement inside findSize() prints the size of a pointer.

How do you find the size of an array?

To determine the size of your array in bytes, you can use the sizeof operator: int a[17]; size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element.

How do I get the size of an array passed to a function in C++?

Using sizeof() function to Find Array Length in C++ The sizeof() operator in C++ returns the size of the passed variable or data in bytes. Similarly, it returns the total number of bytes required to store an array too.

When array is passed to function and is passed?

In case of an array (variable), while passed as a function argument, it decays to the pointer to the first element of the array. The pointer is then passed-by-value, as usual.


2 Answers

The other answers overlook one feature of c++. You can pass arrays by reference, and use templates:

template <typename T, int N> void func(T (&a) [N]) {     for (int i = 0; i < N; ++i) a[i] = T(); // reset all elements } 

then you can do this:

int x[10]; func(x); 

but note, this only works for arrays, not pointers.

However, as other answers have noted, using std::vector is a better choice.

like image 177
Evan Teran Avatar answered Sep 23 '22 01:09

Evan Teran


If it's within your control, use a STL container such as a vector or deque instead of an array.

like image 40
Fred Larson Avatar answered Sep 24 '22 01:09

Fred Larson