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

> Pointer arithmetic I have always heard of pointer arithmetic but now I understand why it’s so useful. Taking a pointer to the first element in an array and incrementing it to iterate through it’s elements is elegant and more efficient than taking an integer i and using it as an array index. I wish more languages afforded this.

Trust me, no you don't. Pointer arithmetic is one of the easiest things to screw up in C, and the raw form can be very dangerous to work with.

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.




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


You are correct, of course. But he is correct in saying that this method is elegant. Thus, iterators, which, in a much safer form, can be found in Java and Python and many other places.




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

Search: