# [ECOS] Deciphering ISO C (Chap 6.3.2.3 - Pointers)

Andrew Lunn andrew@lunn.ch
Mon Nov 10 22:16:00 GMT 2003

```> 	cyg_uint16* res_16;
> 	cyg_uint16* p_16;
> 	cyg_uint16 u_16;
>
> 	p_16 = 0x0u;
> 	u_16 = 0x0u;'
> 	res_16 = (p_16 + 0x555u);
>
> The above code yields res_16 == 0xaaa
> I was sort of hoping for 0x555 instead...

>
> Altering the addition line to this:
> 	res_16 = (cyg_uint16*)(u_16 + 0x555);
> corrects the problem...
>
> why?

Pointer arithmetic. Take the following example bits of code....(which probably has many syntax errors etc)

char foo[4]="bar";
char foo1[4];

int  a[]={0,1,2,3};
int  a1[3];

for (i = 0; i < 3; i++)
{
char * pfoo = &foo;
char * pa = & foo1;

*(pfoo+i) = pfoo[i];
*(pa+i) = a[i];
}

Its a contrived way of copying foo into foo1 and a into a1.

You want *(pfoo+i) to be byte by byte since you are copying characters, but
you want *(pa+i) to be word by word since its copying ints.

In
res_16 = (p_16 + 0x555u);

p_16 is of type cyg_uint16 *, so you are adding 0x555 16bit words, ie 0xaaa.

With
res_16 = (cyg_uint16*)(u_16 + 0x555);

u_16 is a plain cyg_uint16, so its not pointer arithmetic, its normal
arithmetic which you then cast to a pointer afterwards.

Andrew

--