- 3

Why not?

Why not output is same in both? 1. int int_arr[]{10,20,30,40,50}; size_t size = *(&int_arr+1)-int_arr; cout<<size<<endl; Output: 5 //fine 2. int int_arr[]{10,20,30,40,50}; int *arr=int_arr; size_t size = *(&arr+1)-arr; cout<<size<<endl; Output: garbage //but why?????

31st May 2021, 7:52 PM
saurabh
saurabh - avatar
4 odpowiedzi
+ 2
In the first example, you are moving forward by sizeof( int_arr ) bytes to the first address after the array, and then subtract the original address, resulting in the number of integers inbetween. However, in the second example, you are trying to compute the difference between two completely unrelated addresses: The address of the variable "arr" itself (advanced by one) and the address "arr" as a pointer points to (the address of the array). Since the pointer is its own variable, there is no connection between the two addresses, and the result is meaningless. Generelly speaking, when an array decays to a pointer, its length information is lost, without any means to compute it. Hence for example in C, the array length has to be explicitly passed as another parameter when passing arrays to functions.
31st May 2021, 9:41 PM
Shadow
Shadow - avatar
+ 1
I'll have to correct myself: &int_arr + 1 is not undefined behavior, but *(&int_arr + 1) is undefined behavior. same in the second example: *(&arr + 1) is UB. So, it's still UB in both cases. Accessing unallocated memory is undefined behavior. You might get five as an output, but one day, on one machine you could get "flying pizza".
1st Jun 2021, 1:38 AM
Lofty
Lofty - avatar
0
It's undefined behavior in both cases. &int_arr + 1 you're accessing invalid memory. At runtime when you cpu reaches definition of int_arr, the memory (that is the size of that array) will be allocated on stack and elements will be initialized (because you have brace initializer list) stack: |10|20|30|40|50| in the expression &int_arr + 1 we have pointer arithmetic, and the result is the address of an invalid memory. You get a memory address that is beyond the size of your array, that was never allocated. result is this memory location | | | |10|20|30|40|50|__||__||__||__||__| so, anything could happen, you could get 5 as a result (and Shadow explained the reasons for that output), but on some other machine you could get something different. Second code is also UB &arr + 1, again, the result of the expression is a pointer that points to a memory address that was never allocated.
31st May 2021, 10:56 PM
Lofty
Lofty - avatar
0
Quanti bro you have said that its undefined behaviour in both cases but in every machine that I have tried this code is giving the correct result for the first code but my query is why the second code is not giving correct result but now I have got it that what is the wrong is happening with my second code....
1st Jun 2021, 12:43 AM
saurabh
saurabh - avatar