Thread: Screen output of array elements

1. Screen output of array elements

Hi,

Could anyone tell me in words what this code is implementing & perhaps tell me what is the screen output?

I think there is an array of 6 elements, via using the pointer this functions is used to manipulate the number elements within the array - as in this case an extra 3 elements have been added to array therefore 9 elements. I am not too sure.....please help!

Code:
```int arr[6] = {4, 2, 5, 11, 8, 14}
int *p;
p = arr + 3;
printf("%d\n", *p);
p--;
printf("%d\n", *p);
(*P)++;
printf("%d\n", *(p+1));```
Thanks

2. This is nothing but pointer algebra.
p=arr+3; means p points to the 4th element, so *p will give you 11. Then p-- will make p to decrement and thus *p will be 5. Then (*p)++ will increment the value pointed to by p which was 5 and thus *p will now be 6. The last one will still point to at 11 coz p wasn't changed but *p was.

3. Originally Posted by BEN10
This is nothing but pointer algebra.
p=arr+3; means p points to the 4th element, so *p will give you 11. Then p-- will make p to decrement and thus *p will be 5. Then (*p)++ will increment the value pointed to by p which was 5 and thus *p will now be 6. The last one will still point to at 11 coz p wasn't changed but *p was.
Okay,

but does p=arr+3 simpley saying 1 + 3=4, 4th element which is 11? (i kno its obvious)

last line of code [code]printf("%d\n", *(p+1));[\code] will still point to at 11? because *(p+1) does seem to confuse the situation.

Cheers

4. When referencing an array object directly, like you do with 'p=arr+3', it returns a pointer to the first element in the array. When summing 3 to it, it is returning the 4th element in the array.

So, basically, the print order will be like this:
Code:
```11 (4th element)
5 (3rd element)
11 (4th element)```

5. Originally Posted by abraham2119
When referencing an array object directly, like you do with 'p=arr+3', it returns a pointer to the first element in the array. When summing 3 to it, it is returning the 4th element in the array.

So, basically, the print order will be like this:
Code:
```11 (4th element)
5 (3rd element)
11 (4th element)```
Understood thanks alot