This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Passing Arrays to Function in C++
(5 answers)
What is array to pointer decay?
(11 answers)
Closed 9 years ago.
I made a function in C++ to find the length of an array. I find the sizeof the array passed in the argument and divide it by the sizeof the variable type. This should work but it always returns 1! Am I missing something obvious? Or does this have to do with pointers and memory? This is my code:
#include <iostream>
using namespace std;
int lengthOf(int arr[]);
int main() {
int x[] = {1,2,3,0,9,8};
int lenX = lengthOf(x);
cout << lenX;
return 0;
}
int lengthOf(int arr[]) {
int totalSize = sizeof arr;
cout << totalSize << endl;
int elementSize = sizeof(int);
return totalSize/elementSize;
}
Output (should be 6 instead of 1):
4
1
I am fairly new so excuse me if this is a bad question.
When passing an array as parameter, it always decays into a pointer. If you want to see the size of the array, you need to pass the array by reference, e.g.:
template <int Size>
int lengthOf(int (&array)[Size]) {
return Size;
}
You should use the pointer.
(sizeof(arr)/sizeof(*arr))
Even though int arr[] looks like you are passing an array, you are actually passing a pointer. int arr[] is equivalent to int* arr when used as a function parameter, this comes from C.
In C++, if you want to pass an array, the proper way is to do it by reference:
template <int N>
int lengthOf(int (&arr)[N]) {
int totalSize = sizeof arr;
cout << totalSize << endl;
int elementSize = sizeof(int);
return totalSize/elementSize;
}
Related
This question already has answers here:
determine size of array if passed to function
(10 answers)
Miscalculation of array size inside a function
(3 answers)
How do I find the length of an array?
(30 answers)
Closed 1 year ago.
I want to make a function in C++ that returns size of any array using pointers:
*(&array + 1) - array.
like this:
#include <iostream>
using namespace std;
void arrayLength(string array[]) {
int arraySize = *(&array + 1) - array;
cout << "Size of the array: " << arraySize << endl;
}
int main ()
{
string myArray[] = {"a", "b", "c", "d"};
arrayLength(myArray);
// Output: It seems to return the size in bytes (different numbers like this: 381286345)
return 0;
}
And this Code works:
#include <iostream>
using namespace std;
int main () {
string array[] = {"a", "b", "c", "d"};
cout << *(&array + 1) - array << endl;
return 0;
}
Nice demonstration why are ordinary raw arrays dangerous.
The issue is with pointer arithmetic and +1. For T* ptr;, ptr+1 advanced the pointer by sizeof(T) bytes, or one T.
In main, &array is of type string(*)[4], so the pointer is incremented by sizeof(string)*4. This leads to the correct size.
On contrary, string array[] in arrayLength() has type string* even if you use []. The increment is only sizeof(string*) in bytes thus leading to incorrect size.
Just use std::array or std::vector with their size().
I agree with the other answer that you should use std::array or std::vector if possible. If however, you are not allowed to use the STL or have other good reasons to use plain C arrays, then there is a possible template solution:
template<class T, size_t N>
size_t getArrayLength(T(&arr)[N])
{
return N;
}
Just call this template with any array as parameter. Note that calling this with a pointer won't work, but at least you get a compiler error instead of weird runtime behaviour.
This question already has answers here:
determine size of array if passed to function
(10 answers)
size of array passed to C++ function? [duplicate]
(7 answers)
Closed 3 years ago.
How do I get the size of bits of an Array from a function
int NumberOfElements(int Array[]);
int main()
{
int Array[] = { 5,5,6,5,5 };
std::cout << NumberOfElements(Array);
}
int NumberOfElements(int Array[]) {
return sizeof(Array);
}
It's returning 4.
Result should be 20.
Arrays decay into pointers when passed as arguments to functions etc.
The size 4 means that the pointer has that size. It does not tell you anything about the number of elements in the actual array.
You may want to use a std::vector<int> instead where the size is part of its interface:
#include <vector>
int main()
{
std::vector<int> Array{ 5,5,6,5,5 };
std::cout << NumberOfElements(Array);
}
int NumberOfElements(const std::vector<int>& Array) {
return Array.size();
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sizeof an array in the C programming language?
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
string a[] = {"some", "text"};
void test(string a[])
{
int size_of_a = sizeof(a) /sizeof(a[0]);
cout << size_of_a;
}
int _tmain(int argc, _TCHAR* argv[])
{
test(a); //gives 0
int size_of_a = sizeof(a) /sizeof(a[0]);
cout << size_of_a; //gives 2
return 0;
}
as u can see in the comment test(a) gives 0 instead of 2 as i would expect. Could someone explain why and how could i correct it? thanks
When you pass an array to a function, it decays to a pointer to the first element of the array and so within your test(string a[]) function
sizeof(a);
actually returns the size of a pointer and not the size of your array.
To prevent array decaing to pointer, you can pass reference to array to the function. But it causes types of array of function formal argument and actual argument must coincide (including their sizes). So you need to use template to make your function work with an array of any size:
template <int N>
void foo(const string (&a)[N])
{
int size_of_a = sizeof(a) /sizeof(a[0]);
cout << size_of_a;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to find the sizeof(a pointer pointing to an array)
I have the following code
int myfunc(char *arr)
{
const int sizearr = sizeof( arr ) / sizeof(char);
}
This yields the size of the pointer, not the size of the char array[17] I passed to the function.
I know that I may use strlen and solve the problem, but is there any way to convert the char*arr pointer back to the char array[17] I passed to the function in order to use the sizeof(char array[17]) ?
If you want to pass an array of 17 chars, you need to pass it by reference (C++ only):
int myfunc(char (&arr)[17])
{
unsigned int const sizearr = sizeof arr;
// ...
}
Or make a template to deduce the size:
template <unsigned int sizearr>
int myfunc(char (&arr)[sizearr])
{
// ...
}
In C, you cannot pass arrays as arguments at all, so it is your responsibility to communicate the array size separately.
Update: As #David suggests, you can fix the array type in C by passing a pointer to the array:
int myfunc(char (*arr)[17])
{
unsigned int const sizearr = sizeof *arr;
// ...
}
int main()
{
char s[17];
return myfunc(&s);
}
No, there is no such way. But in C++ you can make function template parametrized by array size and pass array by reference:
template <size_t size> void myfunc(char (&arr)[size])
{
for(size_t i = 0; i < size; ++i) std::cout << arr[i];
}
// Usage
char array[] = "My char array";
myfunc(array);
No.
There is no such way. The type char * does not contain any information about the "source", i.e. the array. This is why it's said that the array "decays" into a pointer; the pointer has less information than the array.
Also, sizeof (char) is 1.
Not really, because once the array has decayed to a pointer all information regarding its "original" form has been lost. You can always cast the pointer to a char[17] but that's bad practice.
If you really need to have an array, change the function signature to accept an array.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Passing an array as an argument in C++
Sizeof an array in the C programming language?
Can you please explain the output of the following code:
#include<iostream>
using namespace std;
void foo(int array[])
{
int size = sizeof(array) / sizeof(array[0]);
cout<<size<<endl;
}
int main()
{
int array[] = {1,2,3};
int size = sizeof(array) / sizeof(array[0]);
cout<<size<<endl;
foo(array);
return 0;
}
The corresponding output is:
3
2
Both the code inside foo() and inside main() looks similar to me so as to produce the same output, but it does not, can you please explain why?
void foo(int array[])
in C or C++ you cannot pass arrays by value, so the above declaration is interpretted as:
void foo(int * array)
Consider passing the array by reference:
template <size_t N>
void foo( int(&array)[N] )
{
cout << N << endl;
}
You are not passing the array into the function, you are passing the pointer to the array.
That means, in the function foo(), the result of sizeof(array) is the size of a pointer to an array of char, not the size of the array itself, so the function is effectively doing this:
cout << sizeof(int *) / sizeof(array[0]);
In this case size of int * is 8, size of int is 4, so you are getting an output of 2 from the function.