Home > front end >  Subscripting/Indexing a Pointer in C
Subscripting/Indexing a Pointer in C

Time:05-09

I'm working through some code for a class I'm taking, and since I'm not familiar with C I am confused by subscripting pointers.

My assumptions:

& prefixed to a variable name, gives you a pointer to the memory address of that value and is roughly inverse to * prefixed to a variable name, which in turn gives you the value that resides at a particular memory address.

Pointers are subscriptable, so that ptr[0] == ptr and ptr[n] == ptr (n * data_bytes), where data_bytes depends on the particular type of the pointer (eg. 4 bytes wide for 32-bit ints).

The Problem:

When I want to subscript the memory address, I have to put it in a variable first, and I don't understand why I can't just subscript the variable directly.

Minimal Code Example:

#include <iostream>

using namespace std;

int main() {

    int val = 1;
    int *val_ptr = &val;

    cout << &val << endl;

    // works
    cout << val_ptr[0] << endl;

    // does not work
    // cout << &val[0] << endl;

    return 0;
}

Addendum

I am aware of some related questions, but they didn't really help me understand this specific issue.

I looked at:

and while this is almost certainly a duplicate (I will hardly be the first person that's confused by pointers), or maybe even has an answer that I overlooked in the linked questions, I'd appreciate any help!

CodePudding user response:

As per Ted Klein Bergmann's comment, there was a problem with operator precedence.

[] is considered before &. Do (&val)[0] instead.

So a working example would be

#include <iostream>

using namespace std;

int main() {

    int val = 1;

    // does work now
    cout << (&val)[0] << endl;

    return 0;
}
  • Related