Malloc works without type cast before malloc C/C++

c, casting, malloc, memory, pointers

Solution

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.

Problem

I am learning about malloc function & I read this: ``` ptr= malloc(sizeof(int)*N) ``` Where `N` is the number of integers you want to create. The only problem is what does ptr point at? The compiler needs to know what the pointer points at so that it can do pointer arithmetic correctly. In other words, the compiler can only interpret `ptr++` or `ptr=ptr+1` as an instruction to move on to the next integer if it knows that the ptr is a pointer to an integer. This works as long as you define the variable ptr to be a pointer to the type of variable that you want to work with. Unfortunately this raises the question of how malloc knows what the type of the pointer variable is - unfortunately it doesn't. To solve this problem you can use a TYPE cast. This C play on words is a mechanism to force a value to a specific type. All you have to do is write the TYPE specifier in brackets before the value, i.e.: ``` ptr = (*int) malloc(sizeof(int)*N) ``` Questions I have seen many places that they don't use `(*int)` before the malloc & even implementing a linked list with no errors. Why is that? Why do pointers need to know anything except the size of memory they are pointing to?

Original source

Related problems