sizeof not returning the correct size of arr | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

sizeof not returning the correct size of arr

I have this code I wrote in this app #include <iostream> using namespace std; void sizeofarr(int arr[]); int main() { int a [5]; cout << "size of arr before func " << sizeof(a) << endl; sizeofarr(a); return 0; } void sizeofarr(int arr[]){ cout << "size of arr in func " << sizeof (arr) << endl; } my function takes an arr as it's parameter and in the main i create a simple arr and print the size of it. works perfectly, however when I send the Same arr to the function and print it's size he always print 4! why is it doing that? what am I doing wrong? please help I'm new at c++ thanks in advance!

20th Jul 2016, 11:33 AM
Eli Brown
Eli Brown - avatar
4 Answers
0
its because sizeof returns Bit length of the whole array. you have to do: size = sizeof(array) / sizeof(array[0])
20th Jul 2016, 11:48 AM
Steven
Steven - avatar
0
I know that the sizeof operation returns the bit length of whole arr and in the main he does exactly that! the problem is in the function sizeofarr(int arr[]). here he just prints 4 witch I believe is the bit length of first element
20th Jul 2016, 12:03 PM
Eli Brown
Eli Brown - avatar
0
doesn't matter if you call a function or do it in main. what matters is what i said. even in your function you do not divide! So whatever you do you will always end with the wrong result. and yes the output of your function is the bitlength of one array field. to take your Sample. you have an array int of 5: int=int16=4bit memory. 1 field =4bit * length 5= 20bit memory. to get the array length you have to divide 20/4=5 what assumes sizeof(arr) / sizeof(array[0]) = 5 your array has a length of 5
20th Jul 2016, 12:25 PM
Steven
Steven - avatar
0
I see what your saying. thanks for the help!
20th Jul 2016, 12:33 PM
Eli Brown
Eli Brown - avatar