You have no control over what the specific address is of the block returned by new. Why should you care what the address of the block returned is? This is like complaining that at the coat check in a restaurant they always give you the same number: The number is only a mechanism to recover your coat, so it doesn't really matter what it is.
Minor issues with the code you posted:
* You didn't use
- Code: Select all
tags around it.
* p is initialized to a value (NULL) that is never used.
* There is no delete[] in your code, so you are technically leaking memory (it's just a good habit to always delete what you new).
* To print addresses you should use "%p" as the format, not "%X". "%X" expects an unsigned int, which may or may not be able to hold a pointer, depending on the platform. "%p" actually expects a pointer of type `void *', so a cast should be used.
* Those header files ending in ".h" are obsolete (there is a sticky somewhere about why you shouldn't use them).
* You don't really need anything in <iostream.h> or <stdlib.h>.
- Code: Select all
#include <cstdio>
int main() {
int *p = new int[2];
std::printf("Address of p = %p\n", static_cast<void *>(p));
delete[] p;
}