Malloc works without type cast before malloc C/C++
Before you can use ptr
, you have to declare it, and how you declare it is the pointer becomes.
malloc
returns void *
that is implicitly converted to any type.
So, if you have to declare it like
int *ptr;
ptr = malloc(sizeof(int)*N);
ptr
will point to an integer array, and if you declare like
char *ptr;
ptr = malloc(sizeof(char)*N);
ptr
will point to a char array, there is no need to cast.
It is advised not to cast a return value from malloc
.
But I have seen many places that they don't use (*int) before the malloc & even I made a linked list with this and had no errors. Why is that?
Because they (and you also surely) declared the variable previously as a pointer which stores the return value from malloc
.
why do pointers need to know anything except the size of memory they are pointing to?
Because pointers are also used in pointer arithmetic, and that depends on the type it is pointed to.