Allocating memory to char* C language

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

    Note that:

    1. Strings are zero-terminated (\0), and strlen() doesn't count it;
    2. By definition, sizeof(char) is 1 (byte), so it's not required;
    3. If you use a C (not C++) compiler, there's no need to cast it to char *;

    So that would be:

    char *tempSides = malloc(strlen(inSides) + 1);
    

    Still, if you want to duplicate the contents of inSides, you can use strdup, e.g.:

    char *tempSides = strdup(inSides);
    if (tempSides != NULL) {
        // do whatever you want...
        free(tempSides);
    }
    

提交回复
热议问题