[NTLUG:Discuss] OT C question
Spicerun
spicerun at verizon.net
Sat Feb 18 10:40:09 CST 2006
If I may (not that I'm some great expert or anything), can I recommend
that Integers not be directly added to a pointer, but that the pointer
is incremented or decremented to thr right position?
IE-
Aptr++;
Aptr += 7;
Aptr[7];
Will work (my preferred ways), but
Aptr + 1;
Aptr + 7;
aren't particularly good practice. Your examples currently work right
now because Aptr is a char pointer, whose unit size is 1 byte (8 bits),
but if Aptr was an integer pointer whose unit size was 4 bytes (on an
x86 processor), you'd be moving the pointer to bytes within your integer
and not get the results you're looking for. Incrementing or
Decrementing the pointer will insure that you really are going to the
next element of your array rather than a byte inside of your current
element.
My rule of thumb is to never add Integers to any type of pointers.
Just my $.02
--Spicerun
Paul M Foster wrote:
>
> The printf expressions above should be:
>
> printf("%c\n", *(Aptr + 1));
> printf("%c\n", *(Aptr + 7));
>
> The "contents of" operator (*) binds more tightly than the addition
> operator (+), so in your code, you're just incrementing the contents
> of the pointer location, rather than incrementing the pointer.
>
More information about the Discuss
mailing list