Hello I noticed this weird issue when using multiple pointer structures at the same time. Can somebody explain to me what is causing it ?
#include <iostream>
using namespace std;
typedef struct A{
int x;
}a;
int main()
{
a *a1, *a2;
a1->x = 3;
cout << a1->x << endl; // display "3"
a2->x = 2;
cout << a2->x << endl; // ...does not display "2" ???
return 0;
}
CodePudding user response:
Before assigning the values to your pointers, the pointers have to be initialized properly.
a *a1, *a2;
These pointers are not initialized. They point to some random location in memory. The "new" keyword allocates memory for your structure. You can use it like this:
a *a1 = new A, *a2 = new A;