Post #3594662
2026-07-05 01:17 UTC
the way C and C++ handle pointer addition confuses me. like:
int array[] = {1, 2, 3};
int *arrayPtr = &array;
in this code I think of arrayPtr as a number representing the memory address of array. and given that it’s a memory address, if I add 1 to it it should move 1 byte forward in memory, right? except it doesn’t. if I do that:
arrayPtr += 1;
I just moved 4 bytes forward in memory instead. as in, I increased arrayPtr by 4 because I added 1 to it, because this is an int* and sizeof(int) == 4
if we’re getting as low level as raw memory addresses, why try to abstract away the details of the pointer math? that’s not even an abstraction at that point - that’s just strange counterintuitive behavior. it’s not like it would be that much harder for me to type arrayPtr += sizeof(int); instead of arrayPtr += 1;
Replies (2)
-
@0x57e11a@void.lgbt 2026-07-05 01:30
@kasdeya@cryptid.cafe it imagines this choice was made because the vast majority of times you want to index a pointer or do arithmetic on it, it's an array and you *want* to do it in multiples of the sizeof the pointer type if you want raw memory, that's when you cast down to char* and then cast to specific types when you need to access as a given type
-
@kasdeya@cryptid.cafe 2026-07-05 01:20
also I still think the syntax around pointers and arrays is inconsistent and could’ve been done much better. every time I type *var or var[] or &var I feel a little dirty