Allocating memory to char* C language

后端 未结 7 1632
执笔经年
执笔经年 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:18

    Almost. Strings are NULL terminated, so you probably want to allocate an extra byte to store the NULL byte. That is, even though sides is 1 character long, it really is 2 bytes: {5,'\0'}.

    So it would be:

    tempSides = (char *)malloc((strlen(sides)+1)*sizeof(char));
    

    and if you wanna copy it in:

    strcpy(tempSides, sides);
    

提交回复
热议问题