So I have the following (very simple) code:
int* pInt = new int(32);
std::cout<< pInt << std::endl; //statement A
std::cout<< *pInt << std::endl; //statement B
std::cout << &pInt << std::endl; //statement C
So here's what I think I am doing (I have learned that in C++ I am rarely ever doing what I think I am doing):
Is all of this correct?
A pointer is a variable that stores the address of another variable. Unlike other variables that hold values of a certain type, pointer holds the address of a variable. For example, an integer variable holds (or you can say stores) an integer value, however an integer pointer holds the address of a integer variable.
You can print a pointer value using printf with the %p format specifier. To do so, you should convert the pointer to type void * first using a cast (see below for void * pointers), although on machines that don't have different representations for different pointer types, this may not be necessary.
Pointers are just memory address. So a pointer to an int means a variable whose value is the memory address of an int, and a pointer to a pointer to an int means a variable whose value is the memory address of a pointer to int, and the value of that pointer to int is a memory address of an int.
No, it is no valid to assign a pointer to an integer.
Your second statement is wrong. You allocate a new int off the heap. The compile-time constant "32" does not have an address, and therefore you cannot take it. You create an int whose value is 32. This is not the same thing.
int* pInt1 = new int(32);
int* pInt2 = new int(32);
pInt1 and pInt2 are not equal.
Oh, one last thing- C++ is a pretty strongly typed language, and it's pretty unnecessary to prefix variable names with type data. This is called Hungarian Notation, it's very common in Microsoft C libraries and samples, but generally unnecessary here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With