C语言字符串分割函数splitString的错误与修复
C语言字符串分割函数splitString的错误与修复
以下代码展示了一个C语言实现的字符串分割函数splitString
,但其中存在一些问题:cvoid splitString(const char* input, char* output[], int* count) { *count = strlen(input); for (int i = 0; i < *count; i++) { output[i] = malloc(2); snprintf(output[i], 2, '%c', input[i]); } }
问题分析:
- 内存分配不足:
output[i]
分配的内存空间不足以存储一个字符及其结尾的空字符('�')。应将malloc(2)
修改为malloc(2 * sizeof(char))
,确保分配足够的内存空间。2. 计数错误:count
被设置为输入字符串的长度(strlen(input)
),而实际上它应该表示分割后的子字符串数量。应在初始化count
时将其设置为0,并在每次成功分割出一个子字符串后递增。
*修复后的代码:cvoid splitString(const char input, char output[], int count) { *count = 0; int input_length = strlen(input); for (int i = 0; i < input_length; i++) { output[*count] = malloc(2 * sizeof(char)); snprintf(output[*count], 2, '%c', input[i]); (*count)++; }}
修复后的代码能够将输入字符串正确分割为子字符串,并将每个子字符串存储在output
数组中,同时更新count
以表示分割后的子字符串数量。
总结:
在编写C语言代码时,尤其是在处理字符串和内存分配时,需要格外小心,避免出现内存错误和逻辑错误。

原文地址: http://www.cveoy.top/t/topic/2wn 著作权归作者所有。请勿转载和采集!