return of malloc() function

malloc() function is said to return a null pointer or a pointer to the allocated space. Suppose for a string we make the statement:

char* ptr =  malloc(size)  

Isn't ptr a pointer that would point to a pointer?
Isn't :

char** ptr = malloc(size)  

supposed to be the correct way to declare the pointer to char?

The compiler however doesn't give a warning when we do either, the warning it does give is for the format specifier if used.

How should we declare this and why? Also, how would char** be used?


The char * denotes a char pointer. Malloc will return a void * pointer (that will be automatically converted to whatever pointer you're trying to assign).

The char ** denotes a char * pointer. This is a pointer to a pointer.

If you think of a pointer as a map you have that char * is a map to a char, void * is a map to something mysterious and char ** is a map to another map that leads to a char. So

char* ptr = malloc(size);

Is the correct one, because you want a map to something, not a map to a map.


No, 'ptr' would contain the pointer returned by 'malloc'. You are assigning the returned pointer, not taking its address.


  • *ptr is a pointer to a char, which is often used to manage an array or a string.

  • **ptr is a pointer to a pointer to a char, which is often used to
    manage a matrix (array of arrays) or a string array.

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

    上一篇: 而不是void *?

    下一篇: malloc()函数的返回