+ 4
Array in function
Unable to understand different size of array in main function and user defined functions Refer below code : https://code.sololearn.com/cTKDK147biD4/?ref=app
8 odpowiedzi
+ 5
C++ doesn't maintain the size of the array. It expects the programmer to. The only place that you can calculate the size is within the scope of the original definition. If you want it to be remembered, use one of the standard templates.
+ 3
strange behaviour... array is passed by reference and hence no other copy gets created during function calls, still size is not maintained...
Never thought this behaviour... I have come across many code snippets to complete function (providing coding experience) and there also size is passed as argument to the function in case of array... I thought it was just redundant till today..
thank you for this information...
+ 2
nonzyro sizeof(array) in function test 8(64 bit CPU)..here array is pointer so it is showing size of pointer and sizeof(array[0]) is 4 bytes, that's why we get 2.
+ 2
nonzyro
After some research and experiment, it turned out that It's not a mystery. What sizeof(int *) return is an architecture dependent* size of an integer pointer.
SL incorporates GCC on a 64bit Windows server machine. So, the result of the
sizeof(int *) / sizeof(int)
would be 8 / 4 = 2
_____
* The memory layout in a 32bit machine for addressing an integer array (pointer to array's elements) as above would be like
00 00 00 04 <-0x000
00 00 00 06 <-0x004
00 00 00 03 <-0x008
00 00 00 01 <-0x00C
FF FF FF FF <-0x010
and in 64bit as
00 00 00 00 00 00 00 04 <-0x000
00 00 00 00 00 00 00 06 <-0x008
00 00 00 00 00 00 00 03 <-0x00F
00 00 00 00 00 00 00 01 <-0x017
FF FF FF FF FF FF FF FF <-0x01F
And please consider that array's name isn't a pointer, though in most cases will be converted to pointer. Thus, sizeof(arr) and sizeof(arr+0) would be different, especially on a 64bit machine.
+ 1
John Wells is right. even you try like below then also it won't work.
void Test(int array[])
because c,cpp doesn't maintain array's size.
+ 1
I believe that the sizeof operator is functioning correctly:
You're querying the size of the pointer in Test() named "array".
The bigger mystery is why it returns 2 (16-bit) instead of at least 4 (32-bit).
Perhaps it's an optimisation (squeeze an address into an unsigned short if it fits?) or is my rusty brain in need of grease?
Any hypothesise?
+ 1
Thanx AK-47 I realised as per my last post. Good reference, though.
0
SagaTheGreat 💯 Ah, I missed the "sizeof(array[0])" part! I saw a / and my mind's eye thought // (comment) >_< I see now it was a division sign (I scan too quick through code, lol). The line was: pointer size divided by sizeof int!!
Baka me!
Thanks for pointing (no pun intended) that out. I must remember Playground is on 64-bit arch, too.