Home > Software engineering >  How do I get the address of the value that a pointer is pointing to in C?
How do I get the address of the value that a pointer is pointing to in C?

Time:10-11

I'm trying to get the address of a value which I'm not allowed to directly reference to.

int main() {
  int a = {1, 2, 3, 4};
  int* ptr   = &arr[0];
  // ptr is incremented an unknown number of times
}

After the pointer has moved an unknown number of times, I need to know the address of the value the pointer is pointing to. Say if *ptr is now 3, I need to know the address of 3 without referencing the array. Is it possible?

CodePudding user response:

An address must point at an object or function, and is thus also known as a pointer to object or function. Let's deconstruct your question into premises:

¹/ you have an int, just one (not an array) with extra (erroneous) initialisers. That's a bit strange. Maybe you meant int a[] = /* ... */. On this note, there is no 3 stored because you only have space for one value in this object.

²/ you have a pointer to int object, this is called ptr and it's initialised to &a[0], which is a reference op &a combined with a dereference op ([0]); these ops cancel each other out so your ptr declaration is actually equivalent to int *ptr = a;, which is also erroneous. Perhaps you meant int *ptr = &a; or, assuming you corrected the declaration for a (as per point 1), then your code (or the shorthand version, without the unnecessary dereference reference) is okay.

I need to know the address of the value the pointer is pointing to.

As previously noted, pointers don't point at values; they point at objects or functions (or nothing or garbage, both exceptions for which this question isn't relevant)... and addresses are pointers that point at objects or functions, so if you have a pointer pointing at an object you already have the address.

Say if *ptr is now 3, I need to know the address of 3 without referencing the array.

You already have the address, and you're dereferencing it (*ptr) to obtain the value; ptr is storing an address, right? This is why Jonathan Leffler commented describing this question as tautologous; the very pointer you dereference to obtain the value is also (by definition) an address for the object you intended to be storing 3.

Your confusion is common and (among other common confusions that you're bound to ask about) would be best corrected by a decent textbook, such as K&R2e (do the exercises as you stumble across them). Alternatively, there are literally hundreds of frequently asked questions; you could read the 220ish pages and it'd be quicker and more reliable than asking all of these questions and trusting all of the answers...

  • Related