鉴于:
char test[] = "bla-bla-bla";
Run Code Online (Sandbox Code Playgroud)
哪两个更正确?
char *test1 = malloc(strlen(test));
strcpy(test1, test);
Run Code Online (Sandbox Code Playgroud)
要么
char *test1 = malloc(sizeof(test));
strcpy(test1, test);
Run Code Online (Sandbox Code Playgroud)
Tom*_*zyk 24
这将适用于所有以null结尾的字符串,包括指向char数组的指针:
char test[] = "bla-bla-bla";
char *test1 = malloc(strlen(test) + 1);
strcpy(test1, test);
Run Code Online (Sandbox Code Playgroud)
您将无法获得指向char*或const char*使用的数组的正确大小sizeof.因此,该解决方案更通用.
char test[]="bla-bla-bla";
char *test1 = malloc(strlen(test) + 1); // +1 for the extra NULL character
strcpy(test1, test);
Run Code Online (Sandbox Code Playgroud)