i have just started learning data structures and was trying to implement linked list.
i wanted to know why memory allocation is necessary for the pointer variable i am declaring.
my doubt is when i am declaring a new pointer of list type i am creating doesn't it get the required memory allocated automatically?why i have to specifically assign it?
If you are declaring a pointer it will allocate the memory for the pointer itself. If you want to have dynamic memory you need to allocate it explicitly
The program just happens to work in the first case. In reality, you are stomping memory
somewhere.
1 2 3
int main() {
int x;
}
declares a variable named x of type int. The variable is allocated on the stack.
1 2 3
int main() {
int* px;
}
declares a variable named px which is of type pointer-to-int. px is allocated on the stack.
The integer it points to has to exist somewhere in memory, right? But where is the int?
You have to allocate that memory yourself and point px to the memory.
px = newint;
"new int" allocates memory to store an int and returns a pointer to it. We then assign the pointer
to px.
but i never needed to allocate memory in such simple cases(the example you've mentioned) but reading your reply i think it is a good practice to allocate memory.