Operating System - HP-UX
1753935 Members
9902 Online
108811 Solutions
New Discussion

Re: Shared Memory problem (pointer arithmetic)

 
kenlt
Occasional Advisor

Re: Shared Memory Problem

On further reflection (and before anyone else says it :-) it's not garbage, it's adding 48 * the size of the structure, which is expected. I just wasn't looking at it that way. Casting the pointer as a long is what made it work.

 

Ken

 

Dennis Handly
Acclaimed Contributor

Re: Shared Memory problem (pointer arithmetic)

>It was a very obscure little pointer arithmetic problem. Seems that if you have a pointer to a structure and add an integer to it, you get garbage.

 

No, this is well defined by the C and C++ Standards.  The result of ptoT + N is &ptoT[N] and is the same as

(T*)((char*)ptoT + N * sizeof(T)).

 

 >Casting both the address and the int as a long fixed it.

 

The proper fix is to cast the pointer to a char*, then add, then cast back to the right type.