```c #include <stdio.h> #include <stdlib.h> #include <string.h> // 定义字符串分离函数 char split(char *str, char *splitor) { int count = 0; // 记录分离后的字符串数量 char *p = str; // 临时指针 char *token; // 先计算分离后的字符串数量 while ((token = strtok(p, splitor))!= NULL) { count++; p = NULL; } // 为分离后的字符串数组分配内存 char result = (char )malloc((count + 1) * sizeof(char *)); // 重置指针 p = str; int i = 0; // 进行实际的分离操作并存入结果数组 while ((token = strtok(p, splitor))!= NULL) { result[i] = (char *)malloc(strlen(token) + 1); strcpy(result[i], token); i++; p = NULL; } result[count] = NULL; // 以 NULL 结尾 return result; } int main() { char str[] = "apple,banana,cherry"; char splitor[] = ","; char splitResult = split(str, splitor); // 输出分离后的结果 int i = 0; while (splitResult[i]!= NULL) { printf("%s\n", splitResult[i]); free(splitResult[i]); // 释放每个字符串的内存 i++; } free(splitResult); // 释放结果数组的内存 return 0; } ``` 额外需要注意的逻辑点: 1. 要确保输入的字符串和分隔符有合理的值,避免空指针或异常字符。 2. 内存的分配和释放要匹配,避免内存泄漏。 3. 处理字符串长度时要小心,防止越界访问。 [2024-12-09 21:37:47 | AI写代码神器 | 454点数解答]