-2
char mem[8];
uint64_t *memory{(uint64_t*)(void*)&mem[0]};
std::cout << "diff: " << (void*)memory - (void*)(&mem[0]) << std::endl;

Trivial example, error message with gcc is:

error: invalid use of ‘void’
std::cout << "diff: " << (void*)memory - (void*)(&mem[0]) << std::endl;
FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225

2 Answers2

1

invalid use of void, why?

It's because size of void* (item that stored at this pointer) is unknown .

If you want to calculate distance between pointers in bytes, cast them to pointers of something 1-byte-sized (char*, unsigned char*, uint8_t*, etc.):

std::cout << "diff: " << (uint8_t*)memory - (uint8_t*)(&mem[0]) << std::endl;

ikleschenkov
  • 972
  • 5
  • 11
  • What happens if I convert them to `(uint64_t*)` by the way? My assumption would be the difference would still be the same, measured in byte? – FreelanceConsultant Aug 10 '17 at 16:44
  • @user3728501 it will measure the distance in the `uint64_t` (8bytes) rounded to bottom. For example, distance `2 bytes` will be the `0 uint64_t` – ikleschenkov Aug 10 '17 at 16:46
  • "distance 2 bytes will be the 0 uint64_t" - this doesn't make any sense? – FreelanceConsultant Aug 10 '17 at 17:38
  • @user3728501 well, it's because it's wrong to count in `uint64_t` when you store `uint8_t` at pointer. Use 1-byte pointers to calc the size (distance) in bytes and pointer to the actual stored items (plain types, objects, structures) to calculate items count. – ikleschenkov Aug 10 '17 at 19:40
0

You can't perform pointer arithmetic with void pointers - see here. This is due to void not having a defined "size", whereas eg. with int *x, you know that x+1 is going to be sizeof(int) bytes further along that the address of x.

You can also test it here - removing either of the expressions on the sides of the - will let it compile.

hnefatl
  • 5,860
  • 2
  • 27
  • 49