Static and dynamic memory allocation in C++
This question already has an answer here:
The left side is an int
, the right side is creating an int *
(pointer)
You want:
int * ptr = new int;
Or if you want to do static allocation
int num; // = 5; Will initialize num to 5
Your claim is correct.
left part (ptr) is of static memory allocation.
right part (new int) is of dynamic memory allocation.
In other words, the right part return an int *
, a (dynamically allocated) pointer to int
. You can't assign it to a (statically allocated) variable of int
type.
I would like to explain some things about your code.
The part
new int
is considered 'dynamic allocation' but actually it allocated in the heap memory.
declaring
int ptr
is not considered 'static allocation' rather it's considered 'automatic' because it is allocated on the stack memory. Note that the heap is a lot bigger than the stack (default stack size per thread in Windows is 1MB), so you won't be able to allocate large arrays on the stack. The heap on the other hand is theoretically has 4GB of memory address space although only 2GB are available to a process, and it is also a virtual memory and not physical of'course.
Now, since you denote ptr as just an integer type (and not a pointer), the compiler will fail because you try to assign a memory address to a non-pointer type. Thus, you need to tell the compiler explicitly that this is your intention, and you tell the compiler by casting the memory allocation (which is just a 32-bit address) to int:
int ptr = (int)new int; //allocate an int on the heap and cast the address to an int value
The thing is that now ptr will hold a 32-bit number which is the start address of the memory allocation in the heap. You can't do much with this ptr now because the compiler treat it as a simple integer and not a pointer, so in order to do something meaningful with it (rather than just save the address in an integer value), you will need to cast it to a pointer and only than use it. For instance, initialize the address with some value (let's say the value is 5):
(*(int*)ptr) = 5; //cast to pointer and dereference it.
As you can see the syntax now becomes 'ugly' and very hard to read/understand. If you do things the 'right' way, you would just write it like this:
int* ptr = new int;
*ptr = 5; //dereference the pointer
One more thing, about pointer arithmetics: Since your ptr is just an integer number and not a pointer, when you increment it:
int ptr = new int; //Assume ptr got the address 0x010
ptr++;
//Now ptr will hold the value of 0x011 because the value just got incremented by 1.
But if ptr was a real pointer:
int* ptr = new ptr; //Assume ptr got the address 0x010
ptr++;
//Now ptr will hold the value of 0x014 because the size of an int is 4 bytes
//and the pointer now points to the next address after the allocated integer.
链接地址: http://www.djcxy.com/p/31638.html
上一篇: 使用指针C ++有什么好处
下一篇: C ++中的静态和动态内存分配