DEV Community

Alex Gwartney
Alex Gwartney

Posted on

Understanding Pointers in c++

So I have been going crazy over this one small concept. I have been trying to wrap my head around pointers. To start off with I understand they point to a specific memory adress. My problem comes in when returing a point from a function. More specificly why I can acess the values in it in a specfic manner.

The bottom example is what I am messing with at the moment.I am currently returning a pointer to a int that stores a array as the return value. I place it on the stack to be accessed later. I am also aware this is not the best way of doing things but I am just doing this for practice.



 int* startTheSquare() {
     //Keep the array on the stack to be looped through
    static int ar[2] = { 2,4 };
    //This will set the value of x^2

    return ar;

}

 void outPutValuesToCompute() {

    int* get = startTheSquare();


    for (int i = 0; i<2; i++) {
        cout << "Values" << get[i];
    };
 }

int main()
{
    outPutValuesToCompute();
    return 0;
}


Enter fullscreen mode Exit fullscreen mode

The part that is tripping me up is why can I point to the memory address of this return type here.


int* get = startTheSquare();
Enter fullscreen mode Exit fullscreen mode

and then just automatically gain access to the array with out the need of de referencing it? I also want to know if I just access one part of the array why when I have to then deference it but I do not have to use a reference value & to access it. Like I would need to do when pointing to a variable?

example of accessing with out the array.

int* get = startTheSquare();
int *store = get;
Enter fullscreen mode Exit fullscreen mode

example of accessing it with the array.

 void outPutValuesToCompute() {

    int* get = startTheSquare();


    for (int i = 0; i<2; i++) {
        cout << "Values" << get[i];
    };
 }
Enter fullscreen mode Exit fullscreen mode

example of pointer with variable

int foo = 10;
int *getFoo= &foo;
cout<<*getfoo
Enter fullscreen mode Exit fullscreen mode

Hopefully all of this makes some sort of sense? Please let me know if I need to clarify any thing.

Top comments (1)

Collapse
 
alexgwartney profile image
Alex Gwartney

Ok so I think I just answered my own question. From here. Esently the array is just a pointer to the first element. So its actually just referencing the value automatically. Which makes more sense of why I can just use the for loop in the way I do to access the array normally. tutorialspoint.com/cplusplus/cpp_p...