What is the difference between following snippets of code?
int main()
{
int *p;
p= (int*)malloc(sizeof(int));
}
and
int main()
{
int *p = (int*)malloc(sizeof(int));
}
What is the difference between following snippets of code?
int main()
{
int *p;
p= (int*)malloc(sizeof(int));
}
and
int main()
{
int *p = (int*)malloc(sizeof(int));
}
The first snippet is two-step, defining a pointer and then, assigning a valid** value to the pointer.
The second snippet declares and initializes the pointer via the call to malloc()
in a single step.
In effect, end results of both the snippet are same. It's more about coding standard guidelines for which one to use.
One suggestion though, in case using the first style, consider initializing the pointer to NULL
to prevent accidental use of the pointer before the assignment.
That said, please see this discussion on why not to cast the return value of malloc()
and family in C
..
** [Note]: provided, malloc()
success.