4

I'm looking at some source code and within the code it has some code I don't fully understand. Below is a basic pseudo example that mimics the part I'm having trouble understanding:

    float *myArray;

    object(){
        myArray = new float[20];
    }

    ~object(){   
    }

    void reset(){
        delete [] myArray;
    }

    void myMethod(float *array){
        for (int i = 0; i < 20; i++){
            array[i] = 0.5f;
        }
    }

Now in another method body there's:

    void mySecondMethod(){
        myMethod(myArray + 10);
    }

It's the second method I don't get: What does it mean when you pass an array pointer and an int into a parameter that wants an array pointer? I'm just trying to bolster my knowledge, I've been trying to search about it but have found no information.

John Bale
  • 433
  • 7
  • 16
  • Basically the same as `myMethod(&myArray[10])`. – Zeta Oct 22 '13 at 15:24
  • `myArray` is a pointer, so `myArray + 10` is simply the address of myArray, plus 10. e.g. the 10th float stored within the array. – Marc B Oct 22 '13 at 15:24
  • possible duplicate of [Pointer Arithmetic](http://stackoverflow.com/questions/394767/pointer-arithmetic) – Erbureth Oct 22 '13 at 15:25
  • Also, I think it should be added: "Don't do that" :) – Derek Oct 22 '13 at 15:27
  • 1
    FYI `10[myArray]` is equal to `myArray[10]` – Sergey Oct 22 '13 at 15:27
  • `myArray` is **not** an array. It's a pointer to `float` and it **points to** an array. So the question is not about "Array plus int" but about "Pointer plus int". Those typically behave the same, but muddling the difference between an array and a pointer will bite you in unexpected places. – Pete Becker Oct 22 '13 at 15:36

2 Answers2

7

It simply means "the address of the 11th element in this array".

This is an example of pointer arithmetic, a core feature of C (and also of C++ although it's perhaps considered a bit "low-level" there).

The expression means "take the address of the first element of myArray, and add the size of 10 elements to that".

It works the same as myArray[10], since the indexing operator is really sugar for *(myArray + 10).

unwind
  • 391,730
  • 64
  • 469
  • 606
  • Thanks for this explanation and also telling me what this feature is called, I now have some understanding and can do further reading on the topic. – John Bale Oct 22 '13 at 15:32
  • 1
    Be careful here: `myArray` is **not** an array, so it has no first element. It's simply a pointer to `float`, and `myArray + 10` adds the size of 10 `float`s to the value of `myArray`, that is, it creates a pointer to the 11th element in the array that `myArray` points to. – Pete Becker Oct 22 '13 at 15:34
5
myArray[10]  == *(myArray + 10)

&myArray[10] == myArray + 10
abelenky
  • 63,815
  • 23
  • 109
  • 159