+ 1

i can add or subtract pointers but not multiply or divide why?

2nd Jan 2018, 5:24 PM
shobhit
shobhit - avatar
3 Respuestas
+ 5
Pointers are represented by numbers, but they have different meaning. As aklex is saying, pointer += 1 isn't even the same thing for all pointers and depends on the pointer type. So it's unclear how multiplication even looks like! If you really insist on multiplying addresses, you can cast a pointer to a number. something* my_pointer; long number = reinterpret_cast<long>(my_pointer); And you can do it in the other direction too. I hope it's obvious that you shouldn't ever use this for serious code, ha!
2nd Jan 2018, 6:39 PM
Schindlabua
Schindlabua - avatar
+ 4
It wouldn't make much sense to divide or multiply a pointer, while adding and subtracting does. When you add a pointer it's essentially doing the equivalent of: Address += sizeof(Type) Which is useful for pointers to contiguous memory, like arrays.
2nd Jan 2018, 6:04 PM
aklex
aklex - avatar
+ 1
yeah that make sense but aren't pointers just numbers so why shouldn't it be used for mulitiply and divide.
2nd Jan 2018, 6:19 PM
shobhit
shobhit - avatar