Home > Blockchain >  How to properly insert and display data in an dynamically allocated arrays in C ?
How to properly insert and display data in an dynamically allocated arrays in C ?

Time:03-04

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:

enter image description here

Here is the output when displaying them:

enter image description here

My concern is it doesn't output the correct memory address when inputting data.

enter image description here

But when displaying them it seems to have no problem displaying the correct memory address.

enter image description here

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;
}
  • Related