Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does an Array + int do as one parameter?

Tags:

c++

arrays

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.

like image 681
John Bale Avatar asked Dec 15 '22 05:12

John Bale


2 Answers

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).

like image 173
unwind Avatar answered Dec 23 '22 07:12

unwind


myArray[10]  == *(myArray + 10)

&myArray[10] == myArray + 10
like image 43
abelenky Avatar answered Dec 23 '22 05:12

abelenky