r/programminghelp • u/thegodfather444 • Feb 14 '24
C pointers in C
so i'm learning C right now and i have a question about the use of pointers in arithmetic.
so when i declare ptr1 and ptr2 as pointers, and then i write *ptr2=*(ptr2)+ptr1 it works fine.
but if i write *ptr2+=ptr1 which is almost the same as before i get an error. can someone help me understand the += because it seem the problem is there
1
Upvotes
View all comments
Show parent comment
1
u/[deleted] Feb 19 '24
The address of
ptr1is an unsigned integer and may be larger than the signedintvalue thatptr2points to.ptr1should cast to anunsigned long, which is implicitly truncated and converted to anintbefore adding to*ptr2.Here's the error in the GCC compiler without casting
ptr1to anunsigned longfirst:Furthermore, the
+arithmetic should use theunsigned intvalue of*ptr2to prevent signed integer arithmetic overflows.The following code works in GCC with
-pedantic-errorsenabled.Here's the output.