1- why the output of following code is 4?
(in many ways i end up with value of 5)
1 2 3
int i = 5;
int n = (i++-1);
std::cout << n << std::endl;
2- why the printed value is 40?
1 2 3
int(*p)[10] = {NULL};
int k = int((size_t)(p+1) - (size_t)(p));
std::cout << k << std::endl;
(i know the byte size of int is 4 and array of size 10 has a size of 40
bytes, is that right? but i really dont know why size(p+2)= 80, size(p+1) = 40, size(p) =0)
can we say that p is pointing to NULL array so its size 0
and p+1 is pointing to new array which is [10], therefore its size 40
but what about p+2?
c++ is zero indexed. so adding to above, [10] is the 11th element in a 10 element array and therefore junk (and at risk of an out of bounds crash). [0-9] are the available data.
So, the quiz is asking you to play with pointer arithmetic.
I corrected my post above. p is a pointer to an array of ten ints.
Hence, (size_t)(p) is an address converted to a size_t.
(size_t)(p+1) is likewise an address, but (p+1) is a pointer to the next array of ten ints.
Assuming an int is 4 bytes long, an array of ten ints is 40 bytes long. The difference between the two ten-int elements of the array is 40 bytes. So the correct answer is, indeed, 40.