# Thread: Simple Pointers Problem.

1. ## Simple Pointers Problem.

Code:
```
int a[]={0,1,2,3,4};
int *p;
for(p=a+4;p>=a;p--)
{
printf("%d",a[p-a]);
puts("");
}
```
by address airthematic...
let base address is 100 then a+4=108... because int usses 2 bytes....(100+4*2=108)...
so a[p-a] should be a[8]...
and should be error...
but output is...
4
3
2
1
0

why so please someone explain.....

2. Originally Posted by tushars
by address airthematic...
let base address is 100 then a+4=108... because int usses 2 bytes....(100+4*2=108)...
so a[p-a] should be a[8]...
You are being inconsistent

Consider the first iteration. We know that p = a + 4. Hence, by substitution, a[p-a] would be a[a+4-a], which is a[4].

Now, if we consider your argument with addresses: the value of p is 108, and the value of a is 100. p-a = 8. But then we have to divide by 2 (i.e., by sizeof(int)), thus 8/2 = 4. So, you remembered to multiply the constant by sizeof(int) when adding it to the pointer, but forgot to divide by sizeof(int) when subtracting pointers to get an index offset.

3. thanks for your help.... but i really was not knowing that we have to divide it by 2.... anyways thank you....do you know code for 0/1 KNAPSACK PROBLEM... BY DYNAMIC PROGRAMMINg....????

4. I Am Having A Subject Of Computer Graphics In this Sem.... In This Subject Practicals Are Done In 'C'..... But I dont Know Nothing about functions of <graphics.h>.... so please can you suggest some good BEGINNERS book for learning graphics programming using 'C'..... Thanks A LoT.....

Popular pages Recent additions