Thread: referencing to array-values with pointers

1. referencing to array-values with pointers

Hi!

Im not sure why the following output of the following code is:
2 15 6 8 10

Code being:

Code:
#include <stdio.h>

void change(int *b, int n) {
int i;
for(i=0; i<n; i++)
*(b+1) = *(b+i)+5;
}

int main() {
int i, a[] = {2, 4, 6, 8, 10};
change(a, 5);
for(i=0; i<=4; i++)
printf("%d  ", a[i]);

return 0;
}
I mean, from my understanding an array is basically a pointer of the 1st element of the array, i.e. an array is the address of the first element of an array.

So here *b should be basically a and hence the value of 2 - is this right so far?

if so, then *(b + 1) should be just be basically a and hence 4?
But what is happening then?
it is set to *(b + i) + 5, which should be within the first iteration
*(b + 0) + 5, and hence a + 5 and finally this should be 7?

Im not sure how the calc works to be honest and would be grateful for help to understand it. 2. your assigning the value of a + 5 to a{0+1] then your assining 6+5 to a and so on which is why the 2 doesnt change or the 6, 8 and 10 and why a is 15 ( 10 + 5) 3. by adding 1 or i to the pointer is another way of saying b[ 1 ] or b[ i ] 4. Hi!
Thanks for the reply - Im afraid I still do not fully get it. Originally Posted by cooper1200 your assigning the value of a + 5 to a{0+1]
But this should be 7 then? Since a is 2?
then your assining 6+5 to a
when and how?
and so on which is why the 2 doesnt change or the 6, 8 and 10 and why a is 15 ( 10 + 5)
Need to think more about it, because so far I really apparently do not get it. 5. You're only ever changing *(b + 1). You keep assigning to it, so only the last assignment has a net effect, and in that assignment i == 4, i.e., you compute *(b + 4) + 5, which is 15. 6. Originally Posted by laserlight You're only ever changing *(b + 1). You keep assigning to it, so only the last assignment has a net effect, and in that assignment i == 4, i.e., you compute *(b + 4) + 5, which is 15.

so basically 10 + 5, since *(b + 4) should be b, which is 10.
If this is right, I think I get it now with your help - thanks much^^

............... 7. Originally Posted by Placebo so basically 10 + 5, since *(b + 4) should be b, which is 10.
If this is right, I think I get it now with your help - thanks much^^
laserlight's answer is the right one... and you understood perfectly well the equivalence of *(b+n) and b[n].  8. Originally Posted by flp1969 laserlight's answer is the right one... and you understood perfectly well the equivalence of *(b+n) and b[n]. All right, thanks  Popular pages Recent additions Tags for this Thread

#include, changeint, code, int, void 