C++ : Two pointers (supposedly) to the same address. Changing contents of one of them don't change the contents of the other
arduino, c++, pointers
Solution
a = A('A', 'B'); // This sets _data to "AB" and _array will point to _data
In the above line, `A('A', 'B')` constructs a new A and establishes the internal `_array`. Then `a = ...` invokes the default assignment which just copies every member from source to destination. Now, `a._array` points to the char array of the temporary and that is how the invalid results come to be.
To avoid future errors,
- implement an assignment operator
- a copy constructor
- and also let the default constructor initialize _array.
Problem
I am new in C++ and arduino and I not understanding what is going on. The problem is : I have the variables below : ``` char *_array; char _data[2]; ``` When I do : `_array = data;` And then I change the contents of _data, like `data[0] = 'C'`, `data[1] = 'D'`. The contents of _array don't change, and I need to do `_array = _data` again to apply the changes. It seems that they don't point to the same address. The code below is exemplifying this, the third print for me should be `"3CD"` instead of `"3AB"`, but it is not what happens. Could you help me please? I don't understand. Thank you! ``` #include <SoftwareSerial.h> class Base { public: Base() {;}; void setArray(char* array) {_array = array;} char *getArray() {return _array;} private: char *_array; }; class A : public Base{ public: A() : Base() {;}; A(char data1, char data2) : Base() { setData(data1, data2); setArray(_data); } void setData(char data1, char data2) { _data[0] = data1; _data[1] = data2; } char *getData() {return _data;}; private: char _data[2]; }; A a; void setup() { Serial.begin(9600); } void loop() { a = A('A', 'B'); // This sets _data to "AB" and _array will point to _data Serial.write('1'); Serial.write(a.getData()[0]); Serial.write(a.getData()[1]); // This will print "1AB" (as expected) a.setData('C', 'D'); // Here, _data changes to "CD" but _array no Serial.write('2'); Serial.write(a.getData()[0]); Serial.write(a.getData()[1]); // This will print "2CD" (as expected) Serial.write('3'); Serial.write(a.getArray()[0]); Serial.write(a.getArray()[1]); // This will print "3AB" (WHY?!?!?!) Serial.write('4'); a.setArray(a.getData()); // If I call this function, _array changes to "CD" Serial.write(a.getArray()[0]); Serial.write(a.getArray()[1]); //This will print "4CD" (WHY I need to call setArray?) delay(3000); } ```