I've been having trouble trying to properly display the correct memory address so I don't know in which memory address I'm inputting data.
#include <iostream>
using namespace std;
int main() {
system("cls");
int *p = new int[2];
for(int i = 0; i < 2; i ) {
cout << "Enter value for address " << p << ": ";
cin >> p[i];
}
for(int i = 0; i < 2; i ) {
cout << *p << " " << p << endl;
p ;
}
}
Here is the output when inputting data:
Here is the output when displaying them:
My concern is it doesn't output the correct memory address when inputting data.
But when displaying them it seems to have no problem displaying the correct memory address.
CodePudding user response:
Your input loop is displaying the p
pointer as-is (ie, the base address of the array) on every iteration. It is not adjusting the pointer on each iteration, unlike your output loop which does.
You are also leaking the array, as you are not delete[]
'ing it when you are done using it.
Try this instead:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
system("cls");
int *p = new int[2];
for(int i = 0; i < 2; i ) {
cout << "Enter value for address " << &p[i] << ": ";
cin >> p[i];
}
for(int i = 0; i < 2; i ) {
cout << p[i] << " " << &p[i] << endl;
}
delete[] p;
return 0;
}
Alternatively:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
system("cls");
int *p = new int[2];
int *elem = p;
for(int i = 0; i < 2; i ) {
cout << "Enter value for address " << elem << ": ";
cin >> *elem;
elem;
}
elem = p;
for(int i = 0; i < 2; i ) {
cout << *elem << " " << elem << endl;
elem;
}
delete[] p;
return 0;
}