Hacker News new | past | comments | ask | show | jobs | submit login

For sure, treating a pointer as an integer and incrementing by a fixed number of bytes each time is fine, but more often than not languages have this implemented, just as a JIT or compiler optimization.

And here, you've inadvertently pointed out one of the major pitfalls (and amazing virtues) of pointer arithmetic: in C, pointers increment by the size of their data type. You don't add some number of bytes to the pointer, you add the number of elements by which to increment.

In other words, incrementing a uint8_t* will add one byte to the pointer address, but a uint32_t* will add four bytes, and a pointer to a 64-byte struct will add 64 bytes.

Here's an example. This code:

  #include <stdio.h>
  #include <inttypes.h>
  
  struct foo {
  	char bar[67];
  };
  
  int main()
  {
  	struct foo monkey[60];
  	struct foo *zoochild;
  
  	printf("sizeof foo: %zu\n", sizeof(struct foo));
  	printf("sizeof monkey: %zu\n", sizeof(monkey));
  
  	zoochild = monkey; // child points at first monkey
  	zoochild++; // child points at second monkey
  	printf("(monkey + 1) - monkey: %zd\n", zoochild - monkey);
  
  	printf("(bytes) (monkey + 1) - monkey: %zd\n", (uint8_t *)zoochild - (uint8_t *)monkey);
  
  	return 0;
  }
produces this result

  $ gcc -O4 -Wall -Wextra -pedantic -std=c99 ptr.c -o ptr
  $ ./ptr
  sizeof foo: 67
  sizeof monkey: 4020
  (monkey + 1) - monkey: 1
  (bytes) (monkey + 1) - monkey: 67



Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: