-4

I'm trying to wrap my head around pointers but it's confusing at the moment.

When a C compiler comes across a variable in memory it naturally reads the value present. If "X" was equal to 8 then the value of X would be read out as 8.

But when a compiler comes across a pointer in memory, it doesn't read the value of the pointer (the value of the pointer is random) but it instead goes to the address stored in the pointer.

But the thing is, every variable has a value and an address. Why does C specifically go the address of a pointer variable?

I'm not sure how to word this in a way that makes sense.

What is the point of declaring a pointer variable, when we can access the address of any variable using the & operator and print the pointer?

I'm having trouble visualising a pointer variable.

The way I see it now in my head is, every variable has an address and a value. This is a fact. I'm not sure what a pointer variable does since, like a normal variable, it also has a value and an address.

oAUTHo123
  • 29
  • 2
  • 5
    Your third paragraph is wrong , there is no auto following of pointers. You use the `*` operator to follow a pointer. A pointer variable has a value and address just the same as any other variable – M.M May 29 '18 at 09:40
  • @oAUTHo123 a pointer's value is the address of another variable (object, actually, but close enough). – Quentin May 29 '18 at 09:41
  • For your second question [see here](https://stackoverflow.com/questions/162941/why-use-pointers) or search this site for "why use pointers" and the [c] tag – M.M May 29 '18 at 09:42
  • "A pointer variable has a value and address just the same as any other variable". OK so what' the point of using a pointer then? – oAUTHo123 May 29 '18 at 10:05
  • I can make a normal variable point to another variable, can I not? – oAUTHo123 May 29 '18 at 10:05
  • Or is it the case that, a pointer has an address, and also has a place for storing another variable's address, and also has an associated value? – oAUTHo123 May 29 '18 at 10:06

1 Answers1

1

Pointer variables are treated the same as any other variable when it comes to storage.

Given the following declarations

int i = 1;
int *p = &i;

you get something like this:

Item        Address            Value
––––        –––––––            –––––
   i        0x8000                 1    // address values for illustration
   p        0x8004            0x8000    // purposes only

The integer variable i is stored at address 0x8000 and contains the value 1. The pointer variable p is stored at address 0x8004 and contains the address of i.

IOW, the only difference between i and p is the type of value they store and what operations are allowed on them.

As for why we use pointers, they are required in the following cases:

  • To track dynamically allocated memory;
  • To allow a function to modify the value of an input parameter

They’re also useful in building dynamic data structures.

John Bode
  • 119,563
  • 19
  • 122
  • 198