carraysdynamic-memory-allocationmemory-addressstatic-memory-allocation

Is it possible to go through an array with a pointer on a known position in C?


My question needs some explaination :

First, let's consider a 1D array of size n (dynamic or static). Let's call it tab.

We will simplify by assuming the array is stored in memory from address 0x01 to (0x01 + n - 1).

Now consider a pointer called p. And a starting index i, between 0 and n - 1.

Then we do that :

p = &tab[i];

p has know the value of the address 0x0i. (The notation isn't correct, but you get the point).

Can we read tab[i - 1] or tab[i + 1] using p like this ?

int iprev = *(p - 1);
int inext = *(p + 1);

Or simply like this ?

int iprev = p[-1];
int inext = p[1];

And eventually doing this ?

p--;
p++;

And if that is possible for 1D arrays, can it be for multi-dimensions arrays? And how to implement it in C?


Solution

  • As long as p + i (for any i, positive or negative) doesn't go out of bounds in any direction (i.e., it doesn't point to before tab[0] or after tab[n - 1] in your example) then it's okay.

    And remember that for any pointer or array p and index i, the expression *(p + i) is exactly equal to p[i].


    To be more precise, it's okay to have a pointer to anywhere, as long as it's pointing to valid memory when you dereference the pointer.

    Example:

    int tab[N];  // Exact value of N is irrelevant
    int *p = tab;  // Equal to p = &tab[0]
    
    p--;  // After this, p will be pointing out of bounds, this is okay
    
    // Comparing pointers is okay
    if (p < tab)
    {
        /* ... */
    }
    
    printf("Value of *p = %d\n", *p);  // ERROR: Here you dereference the ouf-of-bounds pointer