I’m a bit confused about the difference between when I just declare a variable such as:
int n;
and dynamically assigning memory to a variable using “new” such as:
int m = new int;
I noticed just from working on a simple linked list project that when I’m inserting a new value in the form of an node object, I have to dynamically create a new node object and append the desired value to it and then link it to the rest of my list. However.. in the same function, I could just define another node object, ex. NodeType *N. and traverse my list using this pointer.
My question is.. when we just declare a variable, does memory not get assigned right away.. or what’s the difference?
Thank you!
Prefer automatic storage allocated variables when possible:
over
The reason dynamic allocation is prefered in your case is the way the linked list is defined. I.e. each node contains a pointer to a next node (probably). Because the nodes must exist beyond the point where they are created, they are dynamically allocated.
Yes, you could do that. But note that this is just a pointer declaration. You have to assign it to something meaningful to actually use it.
Actually, both cases are definitions, not just declarations.
creates an un-initialized
intwith automatic storage;creates a pointer to an
int. It’s dangling, it doesn’t point to a valid memory location.creates a pointer and initializes it to a valid memory location containing an uninitialized
int.creates a pointer and initializes it to a valid memory location containing a value-initialized
int(i.e.0).