Thursday, July 30, 2009

Variables with Allocated Memory?

Hello, this syntax of programming is C++, why is there variables that can get memory off the heap? In other words what is the difference between a regular variable and a variable that is a pointer that points to an allocated memory??


ex:


int integer = 10; //Difference between this


int* pinteger = new int(10); //And this





How is it usefull??

Variables with Allocated Memory?
Pointers are extremely useful when designing data structures like a heap or binary tree (or any data structure). Like you said, it allows you to point to the location in memory for a variable. This is not terribly useful for integers, but for more complex objects that may contain multiple variables, it's great.


For example, lets say I have defined a class "node" in which I have 2 ints defined, a and b. If I have a pointer to the node, such as





node* mynode = new node(constructor params);





I can then reference the node like so:





mynode-%26gt;a;





I hope this makes sense... let me know if it doesn't
Reply:I'm not a programmer per se but I believe the main advantage is being able to modify the value of the memory directly instead of creating a copy of the memory.
Reply:the first one is static, the second one is dynamic. you can release it from your memory when you do the second method.


No comments:

Post a Comment