- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- char **My_split(char splt_char,char const*src,int *plength);
- int main()
- {
- char c=',';
- int length,i;
- char **result=
- My_split(c,"abad,effdsafsdafdsafsa,12dfdsfdsafsaedsafsa,12fsfsadfdsafsa",&length);
- for(i=0;i<length;i++)
- {
- printf("%s\\t",*result);
- free(*result++);
- }
- free(result-length);
- return 0;
- }
- //splt_char 为要以这个字符切割, src 为要切割的字符串
- char **My_split(char splt_char,char const*src,int *plength)
- {
- // 返回的字符串数组长度
- *plength=0;
- // 最大的字符串数量和最大的字符数量
- int max_words=3,max_chars=3;
- char *src2=(char *)src;
- // 分配用于保存当前的字符串
- char *cut_str=(char *)malloc(max_chars);
- // 分配用来保存字符指针数组
- char **result_0=(char **)malloc(sizeof(char *)*max_words);
- // 用于结果, 因为 result_0 会 ++ 把初值变掉
- char ** result=result_0;
- // 这个用来释放内存, 还有比较 realloc 分配内存的时候是否变化了
- char **free_result=result_0;
- *result_0=cut_str;
- while(*src2!='\\0')
- {
- if(*src2==splt_char)
- {
- *cut_str='\\0';
- (*plength)++;
- max_chars=3;
- cut_str=(char *)malloc(max_chars);
- if(result_0>=result+max_words-1)
- {
- max_words*=2;
- result=(char **)realloc(result,max_words*(sizeof(char *)));
- if(free_result!=result)// 说明内存位置变化了
- {
- free_result=result;
- result_0=result+max_words/2-1;
- }
- }
- *(++result_0)=cut_str;
- src2++;
- continue;
- }
- // 如果超过了长度就重新分配 (原来长度的 2 倍)
- if(cut_str>*result_0+max_chars-1)
- {
- max_chars*=2;
- *result_0=(char *)realloc(*result_0,max_chars);
- cut_str=*result_0+max_chars/2-1;
- //(char *)realloc(*result_0,max_chars);
- }
- *cut_str++=*src2++;
- }
- if(*(src2-1)!=splt_char)
- {
- *cut_str='\\0';
- (*plength)++;
- }
- return result;
- }
来源: http://www.codesnippet.cn/detail/090720149918.html