Memory address

Hi

I have written the following program

int *a= new int(5);

cout<<a<<endl;
a++;
cout<<a<<endl;
a++;
cout<<a<<endl;
a++;
cout<<a<<endl;
a++;
cout<<a<<endl;
a++;
cout<<a<<endl;


In the first line of code I have defined 5 memory locations. When I run this code I am getting 3 contiguous locations and next three contiguous location.

Why I am not getting 5 contiguous location.(as I have defined 5 contiguous location)

Kindly advice
Regards
Karan
closed account (z05DSL3A)
...new int(5); creates an int with the value of 5. To create 5 ints you need to use ...new int[5];

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int main()
{
    int * a = new int[5];
    
    for (int i=0; i< 5; i++)
        a[i] = 5- i;

    for (int i=0; i< 5; i++)
        std::cout << "[" << a+i << "] = " <<a[i] << std::endl;

    delete[] a;

    return 0;
}
Last edited on
Topic archived. No new replies allowed.