酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

手把手教你编写 C 语言字符串分离函数,避免内存泄漏与越界!

```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. 处理字符串长度时要小心,防止越界访问。 ######[AI写代码神器 | 454点数解答 | 2024-12-09 21:37:47]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]