When to use malloc for char pointers

前端 未结 5 918
醉话见心
醉话见心 2020-12-23 00:19

I\'m specifically focused on when to use malloc on char pointers

char *ptr;
ptr = \"something\";
...code...
...code...
ptr = \"something else\";
5条回答
  •  忘掉有多难
    2020-12-23 00:44

    malloc for single chars or integers and calloc for dynamic arrays. ie pointer = ((int *)malloc(sizeof(int)) == NULL), you can do arithmetic within the brackets of malloc but you shouldnt because you should use calloc which has the definition of void calloc(count, size)which means how many items you want to store ie count and size of data ie int , char etc.

提交回复
热议问题