+ 1

Please explain this code

:#include <iostream>using namespace std;int main(){ int *p = NULL; // Pointer initialized with null p = new int[20]; // Request memory cout <<p; delete [] p; // Delete array pointed to by p return 0;}every time I run this program the address of int[20] changes.Why?

12th Sep 2016, 11:20 AM
Aryan Pandey
Aryan Pandey - avatar
4 Respostas
+ 3
Because it uses dynamic memory, allocated on the heap, which is managed a bit differently from the stack.
12th Sep 2016, 12:02 PM
Zen
Zen - avatar
+ 1
Because on every new instanciation of program it allocates a new address to the variables used in program
12th Sep 2016, 11:33 AM
Umed Jadhav
Umed Jadhav - avatar
+ 1
It is picking the most readily available area in your RAM each time. Because you have background tasks running, the area that is most readily available will vary
13th Sep 2016, 1:43 AM
Cheshire Cat
Cheshire Cat - avatar
0
By creating a pointer that will point to any site, the initial value of the pointer, when it is declared, may contain memory addresses that do not exist. Even pointing to a memory point, it is not likely to point to an object of the appropriate type. Within the array of memory cells will exist zones that contain programs and data, both the user and the operating system itself or other programs, the operating system manages that memory, prohibiting or protecting certain areas. But the pointer, as an object which is also stored in memory, and therefore also have a memory address. When we declare a pointer we are reserving the memory required to store it. By creating a pointer must be assigned, or the address of an existing object, or the one explicitly created during program execution or a known value indicating that does not point to any object, ie the value 0. The operating system more advanced as it is often better memory control. This control translates to prevent access to certain addresses reserved by the system. Int * p = NULL line; does just that
13th Sep 2016, 7:36 PM
Igor Duran
Igor Duran - avatar