Hacker News new | ask | show | jobs
by caf 4032 days ago
You don't need the address of a variable: you can use the plain variable just fine, and most C code does a lot of that.

What a pointer does is add a level of indirection: so instead of having a value "an integer" you can have a value which is "the location of an integer". A variable holding such a value can be assigned the location of any integer variable, and importantly can also be reassigned the location of a different integer variable.

The additional indirection also means that you can link one data structure to another without including one as an integral part of the other.

1 comments

And why is this useful? Well, for high-level folks, pointers are used for roughly the same thing as reference variables in other languages.

For low-level folks, sometimes you need to be able to read from / write to a specific address in memory. So if you have, for instance, a system clock device that always give you the current time if you read address 0x1234, you might do something like this:

uint64 system_time;

uint64 system_time_device = 0x1234; // A pointer to the system time device...

system_time = system_time_device; // read the contents of the memory at address 0x1234 to get the time

For anyone confused, HN's formatting system changed the two asterisks that give this meaning into italics-start and italics-end.

  unit64 system_time;
  unit64 *system_time_device = 0x1234; // set pointer
  system_time = *system_time_device; // read what's pointed to