Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)

If I have the following code:

int* p;
int w=10;
p=&10;

Will the memory allocation for both w and p will be on stack only?

Please correct me if im wrong as I'm a newbie to C++, and please let me know when it is really useful to allocate memory dynamically using a pointer rather than allocating on the stack?

Posted
Updated 25-Aug-09 10:04am
v2

kumar sanghvi wrote:
int* p; //declared pointer to int (statement does nothing)<br />int w=10; //declares and initializes an int to 10, but it won't exist unless you use it<br />p=&10; //this is an error, you probably meant p=&w?

p=&w would do, assuming p is used: give (if it didn't have one yet) w a place on the stack (previously it would probably reside in a register), and set p to that address (eg lea esi, dword ptr[esp+24]), but if the operations on p are simple enough (for the specific implementation, not every theoretically simple enough sequence of operations) to evaluate at compile time it may be optimized to something weird and/or scary.

But it's fine to think of them as being on the stack, the compiler will guarantee that this assumption is true whenever you make it (and if you don't make it, it doesn't matter). They're definitely not on the heap, if that's what you were wondering about.


notes: many simplifications and omissions were made to avoid writing a king-sized post, if you really want to know every little detail you could ask the same question on comp.lang.c++[^], they will be happy to tell you every pedantic little detail. And I don't guarantee that anything in this post was actually true, use the information at your own risk (etc etc)


 
Share this answer
 
kumar sanghvi wrote:
<br />int *p;   //With this statement, you just declared a pointer variable (which will point to an integer)<br />int w=10; //You declared an integer and initialized it. The storage for this variable is on the stack.<br />p=&w;    //You made the integer pointer you earlier declared, point to the integer that you just created on the stack.


the memory allocation for both w and p will be on stack only ...?


Yes, in this case, the pointer is pointing to a memory location, which is on the stack.

kumar sanghvi wrote:
when it is really useful to allocate memory dynamically using pointer than allocating on the stack..?


Pointers are more useful when you need to allocate memory dynamically (typically you don't know how much memory you are going to need).

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900