using sizeof() within a member function [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to find the sizeof(a pointer pointing to an array)
Sizeof array passed as parameter
I have this code:
class total {
public:
void display(int []);
};
void total::display(int *arr)
{
int len = sizeof(arr)/sizeof(int);
cout << len;
}
int main(void)
{
int arr[] = { 10, 0, 0, 4, 20 };
total A;
A.display(arr);
return 0;
}
The output is 1 while I expected it to be the length of array , 5
However if I use the sizeof() statement in main() it displays 5.
So, why is the sizeof() not displaying correct value inside the member function?

sizeof of an array operand yields the size of the array but sizeof of a pointer operand yields the size of the pointer. Pointer and arrays are not the same in C/C++.

The sizeof operator returns the size of the operand. In your case sizeof(arr), the type of the operand is int*. So, the result is either 4 or 8 (depending on the platform, can be also 2 or 1). There is not way to know inside the finction the length of the passed array. Even if you write
void total::display(int arr[5])
{
}
this will not change anything because arrays are converted to pointers when they are used as params of the methods. You can still pass array of any size.

Related

size of array being passed into function [duplicate]

This question already has answers here:
Why isn't the size of an array parameter the same as within main?
(13 answers)
Closed 5 years ago.
Complete example:
#include <stdio.h>
void test(int arr[]) {
int arrSize = (int)(sizeof(arr) / sizeof(arr[0]));
printf("%d\n", arrSize); // 2 (wrong?!)
}
int main (int argc, const char * argv[]) {
int point[3] = {50, 30, 12};
int arrSize = (int)(sizeof(point) / sizeof(point[0]));
printf("%d\n", arrSize); // 3 (correct :-) )
test(point);
return 0;
}
Before passing it to a function, sizeof gives me the correct value. Doing the exact same thing on the exact same array in the function gives weird results. There's one element missing. Why?
When you pass an array into a function in C, the array decays into a pointer to its first element. When you use sizeof on the parameter, you are taking the size of the pointer, not the array itself.
If you need the function to know the size of the array, you should pass it as a separate parameter:
void test(int arr[], size_t elems) {
/* ... */
}
int main(int argc, const char * argv[]) {
int point[3] = {50, 30, 12};
/* ... */
test(point, sizeof(point)/sizeof(point[0]));
/* ... */
}
Also note that, for a similar reason (taking the sizeof a pointer), the sizeof(point)/sizeof(point[0]) trick doesn't work for a dynamically allocated array, only an array allocated on the stack.
Because array is decayed to a pointer when passed as function argument, so sizeof gives you 4 and 8 for 32- and 64-bit platforms respectively.
Also, it's important to understand that sizeof is evaluated at compile time. Since that's the case, it doesn't make sense to expect different output in test() depending on what was passed in. The sizeof calculation was done when the function was compiled.
Because, when it's passed, only the pointer to array is actually being passed.
Your question is also answered at The C Programming FAQ. Question 6.21.
Because in C, C++, and Objective-C, functions cannot actually have array parameters. They only can have parameters that look like array parameters, but they aren't. In your example,
void test(int arr[])
the compiler sees "there is a parameter that looks like an array of int", and it replaces that parameter with a "pointer to int". So the function that you wrote is absolutely, one hundred percent, identical to
void test (int* arr)
Therefore, inside the function sizeof (arr) will give you the size of a "pointer to int".
Because sizeof() does NOT tell you the size of an array in C. It does something completely different.
sizeof C++ reference

Why does sizeof(A), for some array A, not work inside a function? [duplicate]

This question already has answers here:
How do I use arrays in C++?
(5 answers)
Closed 8 years ago.
The following
#include <iostream>
void printArraySize ( int * arr )
{
std::cout << sizeof(arr)/sizeof(int);
}
int main ()
{
int arr [] = {1, 2, 3, 69203};
printArraySize(arr);
return 0;
}
outputs 1 (Proof: http://codepad.org/yKG3mZIz). Explain this nonsense. Does an array forget its size once it enters a function? From what I understand, passing in arr, a memory address, a number, just means making a copy of that number. So sizeof(arr)/sizeof(int) should mean the same thing inside and outside of the function.
In main, arr is an array and sizeof yields the size of the array.
In printArraySize, arr is a pointer to int and sizeof yields the size of the pointer to int object.
In C you cannot pass (directly) arrays to functions, you can only pass a pointer to the first element of the array. To get the size of the array in printArraySize you need to pass it explicitly as an argument to the function.
In C++ you can pass C arrays by reference but you shouldn't use C arrays in the first place but use std::array or std::vector instead.
It is because you check sizeof ( int*) which is sizeof pointer to int. This is because arr passed to function in
int arr [] = {1, 2, 3, 69203};
printArraySize(arr);
decays to a pointer to int. It is just a pointer to integer, first element of array.
C
For doing what you would like to achieve there is a macro often used (for static arrays):
#define ARRAY_SIZE(x) (sizeof((x)) / sizeof((x)[0]))
example:
int arr [] = {1, 2, 3, 69203};
printf( "%d", ARRAY_SIZE(arr));
C++
template<class T, size_t n>
size_t array_size( T(&)[n]) {
return n;
}

Calculate size of array of character pointers [duplicate]

This question already has answers here:
When a function has a specific-size array parameter, why is it replaced with a pointer?
(3 answers)
Closed 8 years ago.
I have the following function in C
int func(char* param1[], int param2[])
{
//Want to calculate size of param1 array
}
I tried
n = sizeof(param1)/sizeof(char*);
but this doesnt give me the correct answer.
Note that the function prototype
int func(char* param1[], int param2[]);
is equivalent to
int func(char **param1, int *param2);
This means the function parameters param1 and param2 are pointers, not arrays. Pointers and arrays are different types.
sizeof(param1) / sizeof(char*);
// equivalent to
sizeof(char **) / sizeof(char *) // always 1
The above expression always evaluates to 1 because size of all pointer types is the same (except for a function pointer on which sizeof operator may not be applied).
That's because you cannot pass an array to a function. What's actually gets passed is a pointer to the first element of the array. The pointer has no size information of the array passed to the function. Therefore, you must explicitly pass the array lengths to your function. It should have the prototype
int func(char *param1[], int param2[], int len_param1, int len_param2);
There are two ways of doing this:
Simplest and most obvious, pass the length in the function argument
Have a NULL at the end of the array (NULL-terminator):
char arr[] = { "what", "so", "ever", NULL }; Then loop:
int i;
for (i = 0; arr[i] != NULL; i++)
...
However, if you're passing an array like the example above to that function (a static one), just pass the length as an argument by using same logic...
func(arr, sizeof(arr) / sizeof(arr[0]);
C isn't smart enough to know the size of an array at runtime. It can only tell you the size of a data type, which is determined at compile-time.
The solution to this is to add a size parameter to the function, like this:
int func(char* param1[], int param2[], int n)
or to use a null-terminated array, so that you can use a loop to iterate through the array:
int func(char* param1[], int param2[]){
int size;
for(size = 0; param1[size] != NULL; size++);
...
The point is, an array in C is just a block of memory that you can happen to treat as a bunch of variables next to each other. There's no built-in way to figure out how many variables are in the block, since there's no built-in way to mark the beginning or end of the block.
char* param1[]
will make param a pointer of type char ** so the result of
n = sizeof(param1)/sizeof(char*);
is sizeof pointer by size of pointer i.e. 1. and its not size of array

Why do sizeof statsements produce different results? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calculating size of an array
Sizeof an array in the C programming language?
Why does sizeof(arr)/(double)sizeof(arr[0]) work and sizeof(arr+0)/(double)sizeof(arr[0]) not work?
And why does sizeof(arr)/(double)sizeof(arr[0]) also not work when arr is passed to a function? Here is the full code example:
#include <iostream>
using namespace std;
int givesize(int arr[])
{
cout<<sizeof(arr)/(double)sizeof(arr[0])<<"\n";
}
int main()
{
int arr[] = {1,2,3,4,5};
cout<<sizeof(arr)/(double)sizeof(arr[0])<<"\n";
cout<<sizeof(arr+2)/(double)sizeof(arr[0])<<"\n";
givesize(arr);
return 0;
}
Output
5
1
1
This happens because arrays decay to pointers when they are passed to functions that take pointers as arguments.
Inside your main, the
int arr[] = {1,2,3,4,5};
declaration is equivalent to
int arr[5] = {1,2,3,4,5};
because the compiler has enough information to calculate the 5 from the aggregate initializer. In the function header, however, int arr[] does not mean the same thing: there is no context around it to tell the compiler that it's anything but a pointer to an integer.
int arr[] in a function argument list is the same as int* arr. Which means that in:
int givesize(int arr[])
{
cout<<sizeof(arr)/(double)sizeof(arr[0])<<"\n";
}
sizeof(arr)/(double)sizeof(arr[0]) is actually sizeof(int*) / (double)sizeof(int). As it outputs 1 that implies a 32-bit platform.
int arr[] as a local variable is not the same as int* arr, hence sizeof(arr)/(double)sizeof(arr[0]) is the same as sizeof(int[5]) / (double)sizeof(int) which evaluates to 5.
Next, sizeof(arr+2)/(double)sizeof(arr[0]) is again the same as sizeof(int*) / (double)sizeof(int), because the type of expression arr+2 is int*.
Inside main, arr has type "array of five ints", but arr+0 has type "pointer to int". When you add zero to arr, you are treating it like a pointer, and as soon as you use an array like a pointer, it gets converted to a pointer.
Why does sizeof(arr)/(double)sizeof(arr[0]) work
Because sizeof(arr) returns the size of the entire array in bytes (let's say 20 assuming int is 32 bits), and sizeof(arr[0]) returns the size of the first int (which is 4 bytes). This will give us 5.
And why does sizeof(arr)/(double)sizeof(arr[0]) also not work when arr is passed to a function?
Because arrays decay into pointers. This means they lose an important piece of information: their size. We cannot directly calculate the size of an array just by a pointer. How would the function even know it is an array to begin with?
C++? Use a template function:
template <typename T, int N>
int getsize(const T (&arr)[N])
{
return N;
}

Why does a C-Array have a wrong sizeof() value when it's passed to a function? [duplicate]

This question already has answers here:
Why isn't the size of an array parameter the same as within main?
(13 answers)
Closed 5 years ago.
Complete example:
#include <stdio.h>
void test(int arr[]) {
int arrSize = (int)(sizeof(arr) / sizeof(arr[0]));
printf("%d\n", arrSize); // 2 (wrong?!)
}
int main (int argc, const char * argv[]) {
int point[3] = {50, 30, 12};
int arrSize = (int)(sizeof(point) / sizeof(point[0]));
printf("%d\n", arrSize); // 3 (correct :-) )
test(point);
return 0;
}
Before passing it to a function, sizeof gives me the correct value. Doing the exact same thing on the exact same array in the function gives weird results. There's one element missing. Why?
When you pass an array into a function in C, the array decays into a pointer to its first element. When you use sizeof on the parameter, you are taking the size of the pointer, not the array itself.
If you need the function to know the size of the array, you should pass it as a separate parameter:
void test(int arr[], size_t elems) {
/* ... */
}
int main(int argc, const char * argv[]) {
int point[3] = {50, 30, 12};
/* ... */
test(point, sizeof(point)/sizeof(point[0]));
/* ... */
}
Also note that, for a similar reason (taking the sizeof a pointer), the sizeof(point)/sizeof(point[0]) trick doesn't work for a dynamically allocated array, only an array allocated on the stack.
Because array is decayed to a pointer when passed as function argument, so sizeof gives you 4 and 8 for 32- and 64-bit platforms respectively.
Also, it's important to understand that sizeof is evaluated at compile time. Since that's the case, it doesn't make sense to expect different output in test() depending on what was passed in. The sizeof calculation was done when the function was compiled.
Because, when it's passed, only the pointer to array is actually being passed.
Your question is also answered at The C Programming FAQ. Question 6.21.
Because in C, C++, and Objective-C, functions cannot actually have array parameters. They only can have parameters that look like array parameters, but they aren't. In your example,
void test(int arr[])
the compiler sees "there is a parameter that looks like an array of int", and it replaces that parameter with a "pointer to int". So the function that you wrote is absolutely, one hundred percent, identical to
void test (int* arr)
Therefore, inside the function sizeof (arr) will give you the size of a "pointer to int".
Because sizeof() does NOT tell you the size of an array in C. It does something completely different.
sizeof C++ reference