Allocating memory to char* C language

后端 未结 7 1590
执笔经年
执笔经年 2021-01-05 06:47

Is it the correct way of allocating memory to a char*.

char* sides =\"5\";

char* tempSides;

tempSides = (char*)malloc(strlen(inSides) * sizeof(char));
         


        
7条回答
  •  执笔经年
    2021-01-05 07:30

    Multiplying the element count by sizeof(char) is a matter of personal preference, since sizeof(char) is always 1. However, if you do this for consistency, better use the recipient pointer type to determine the element size, instead of specifying type explicitly. And don't cast the result of malloc

    tempSides = malloc(strlen(inSides) * sizeof *tempSides);
    

    Of course, when working with zero-terminated strings you have to remember to allocate extra space for the terminating zero character. There's no way to say whether it is your intent to make tempSides a zero-terminated string in this case, so I can't say whether you need it.

提交回复
热议问题