What is the difference between
struct LinkedList *current = malloc(sizeof(struct LinkedList));
and
struct LinkedList *current;
where
struct LinkedList{
int data;
struct LinkedList *next;
}
When I was creating a LinkedList I couldn't achieve most of my desired outcomes with the latter LinkedList declaration.
struct LinkedList *current;defines an object namedcurrentof typestruct LinkedList *and does not specify an initial value for it. If it appears outside a function, the object is initialized to a null pointer. if it appears inside a function, it is not initialized, and the object’s value is indeterminate.struct LinkedList *current = malloc(sizeof(struct LinkedList));defines an object namedcurrentas above, callsmallocto allocate enough memory for an object of typestruct LinkedList, and initializescurrentwith the return value ofmalloc. This would normally appear inside a function, so thatmallocis executed during program execution.That is because
currentwas not pointing to reserved memory, so attempting to use it as a pointer did something bad.