operator precedence and pointer to an array

Hello everyone
I have very basic questions

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?

could you explain please?

Regards
Last edited on
1. x++ is the post increment operator — it increments the value of x after using it, so:
1
2
3
int n = (i++-1);
int n = (5-1);
int n = 4;


2. p is an array of ten pointers to int pointer to an array of ten ints. The value you got is garbage.

Hope this helps.

[edit]Sorry, brain fail.[/edit]
Last edited on
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.
Appreciate your replies.

1.thanks :)

2.It is a quiz test and i dont think a garbage value should be the answer!!!

The question:
After performing the code below, what will be displayed on the screen?
(assume sizeof(int) =4).
1
2
3
4
5
void main(){
  int(*p)[10] = {NULL};
  int k = int((size_t)(p+1) - (size_t)(p));
  std::cout << k << std::endl;
}


The given answers:
A)1 B)2 C)4 D)10 E)40

and the correct answer was 40.

Any comments will be appreciated.
Last edited on
I misread the assignment.

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.


Sorry I misread the code so poorly.
Thank you dear duthomhas.
Topic archived. No new replies allowed.