Search code examples
c++arrayspointersc++17memory-address

Arrays, Pointers and Memory addresses instances confusion in C++


I'm learning and playing a bit with pointers and memory addresses.

The thing is that I've tried doing some moves with instances inside arrays and getting their memory address, and I can't figure out why the following case is not fulfilled if they are supposed to point to the same instance, so I should get the same address.

I would really like to know why this happens, since I think that by calling the address pointed to by the pointer associated with the array, I would be calling the same memory address of the original instance, not a different address of the array.

If there is any confusion or misunderstanding with my question, please feel free to ask anything to understand my problem. I really want to know why this is happening.

Code:

#include<iostream>

#include<string.h>

using namespace std;

class Student {
    int age;
    string name;

    // methods and public variables
    public: Student(int _age, string _name) {
        this -> age = _age;
        this -> name = _name;
    }

    // getters & setters not appearing in this problem
};

int main() {

    Student a1(12, "qwe");
    Student a2(15, "rty");
    Student a3(17, "zxc");
    Student * p = & a1;

    // array of instances
    Student students[] = {
        a1,
        a2,
        a3
    };

    // arrays with pointers
    Student * studentPtr1 = students;
    Student * studentPtr2 = & students[0];

    // this two are the same memory addres
    cout << "&a1 --> " << & a1 << endl;
    cout << "p --> " << p << endl;
    // the rest of these memory addresses are different from a1 but are the same memory address as each other
    cout << "&(students[0]) --> " << & (students[0]) << endl;
    cout << "&(students) :" << & (students) << endl;
    cout << "&(*studentPtr1) --> " << & ( * studentPtr1) << endl;
    cout << "&(*studentPtr2) --> " << & ( * studentPtr2) << endl;
    cout << "studentPtr2 --> " << studentPtr2 << endl;

    // if students[0] is a1 why if a try to get his memory address i get a different one ?.
    // &(students[0]) == &a1 ---> false (why??).

    return 0;
}

Output

&a1 --> 0x7ffeb1d77e30  
p --> 0x7ffeb1d77e30  
&(students[0]) --> 0x7ffeb1d77ec0  
&(students) :0x7ffeb1d77ec0  
&(*studentPtr1) --> 0x7ffeb1d77ec0  
&(*studentPtr2) --> 0x7ffeb1d77ec0  
studentPtr2 --> 0x7ffeb1d77ec0  

Solution

  • student[0] and a1 have the same value, this is true. But they are stored in different locations so their addresses are different.

    Here's another example

    int a = 1;
    int b = 2;
    int c = 3;
    int student[3] = { a, b, c };
    

    Now student[0] == a but &student[0] != &a. Just because student[0] and a have the same value does not mean that they have the same address. This is (I hope) obvious when a and student[0] are integers, but it's just as true when they are objects.