Search code examples
c++arraysnew-operator

Dynamic array with new in c++ - cout array[num]


I am trying to diplay the value stored inside the array but only the value ofarray[0] = 13; is shown. For array[1] = 4; it prints out an adress. I read the introduction of new but that doesnt helped. What is wrong?

std::cin >> _size; //_size > 2
int* array;
         array = new int[_size];
         array[0] = 13;
         array[1] = 4; 

         std::cout << array[0] << std::endl;
         std::cout << array[1] << std::endl;```

console output:
13
0000008CFCF5F518

Solution

  • Your output is weird, try this code and compare it to your entire code, you will understand:

    int *array;
    unsigned _size;
    std::cin>>_size;
    array=new int[_size];
    array[0]=13;
    array[1]=4;
    std::cout<<array[0]<<'\n';
    std::cout<<array[1];
    delete[]array;