Malloc works without type cast before malloc

This question already has an answer here:

  • Do I cast the result of malloc? 27 answers

  • 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.


    Before allocating space for a pointer you need to declare the pointer

    int *ptr;  
    

    Since return type of malloc is void * , it can be implicitly converted to any type. Hence

    ptr= malloc(sizeof(int)*N);  
    

    will allocate space for N integers.


    The only problem is what does ptr point at?

    It points to a block of memory of size sizeof(int) * N .

    The compiler needs to know what the pointer points at so that it can do pointer arithmetic correctly.

    You are not doing any pointer arithmetic in your code, so this does not apply. Returning void * from malloc() is fine because void * can be implicitly converted to and from any object pointer type.

    Also note that casting the return value to (int *) does not change the type of ptr itself. So it doesn't to any good. If ptr was of type void * , then you couldn't perform pointer arithmetic on it even if you wrote

    void *ptr;
    ptr = (int *)malloc(sizeof(int) * N);
    

    How should I explain this better? A variable always has the same type, regardless of which type of value you assign to it (eg in this case, assigning a void * to an int * is fine because there's an implicit conversion.)

    This is why you should not cast the return value of malloc() : it has no benefits. It doesn't help correctness, it can hide errors, and it decreases readability.

    链接地址: http://www.djcxy.com/p/28426.html

    上一篇: 为什么c ++禁止void *的隐式转换?

    下一篇: Malloc在malloc之前没有进行类型转换