代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
void FreeMallocMem(char** pt3, int nCount)
{
int i = 0;
if (pt3 == NULL)
{
return;
}
for (i = 0; i < nCount; i++)
{
if (pt3[i] != NULL)//已经分配内存了
{
free(pt3[i]);
}
}
if (pt3 != NULL)
{
free(pt3);
}
}
void FreeMallocMem1(char*** pt4, int nCount)
{
int i = 0;
char** pt3 = NULL;
if (pt4 == NULL)
{
return;
}
pt3 = *pt4;
if (pt3 == NULL)
{
return;
}
for (i = 0; i < nCount; i++)
{
if (pt3[i] != NULL)//已经分配内存了
{
free(pt3[i]);
}
}
if (pt3 != NULL)
{
free(pt3);
}
*pt4 = NULL;//把实参二级指针,修改成NULL
}
int Split_string(char* instr, char c, char*** p3, int* nrow)
{
int ret = 0;
int i = 0;
int nCount = 0;
if (instr == NULL)
{
ret = -1;
printf("instr NULL error:%d\n", ret);
/*return ret;*/
goto END;
}
char* pt1 = instr;
char* pt2 = instr;
char** pt3 = NULL;
//nCount
do
{
pt1 = strchr(pt1, c);
if (pt1 != NULL)
{
if (pt1 - pt2 > 0)
{
nCount++;
pt1 = pt1 + 1;
pt2 = pt1;
}
else
{
ret = -5;
printf("instr error:%d\n", ret);
/*return ret;*/
goto END;
}
}
else
{
ret = -6;
printf("NO ',' error:%d\n", ret);
/*return ret;*/
goto END;
}
} while (*pt1 != '\0');
*nrow = nCount;
//
nCount = 0;
pt1 = instr;
pt2 = instr;
pt3 = (char**)malloc(nCount * sizeof(char*));//char* Array[nCount]
if (pt3 == NULL)
{
ret = -1;
printf("pt3 malloc error:%d\n", ret);
/*return ret;*/
goto END;
}
memset(pt3, 0, nCount * sizeof(char*));
//copy data
do
{
pt1 = strchr(pt1, c);
if (pt1 != NULL)
{
if (pt1 - pt2 > 0)
{
int len = pt1 - pt2;
int strlen = pt1 - pt2 + 1;
pt3[nCount] = (char*)malloc(strlen * sizeof(char));
if (pt3[nCount] == NULL)
{
ret = -2;
printf("pt3[nCount] malloc error:%d\n", ret);
/*return ret;*/
goto END;
}
strncpy(pt3[nCount], pt2, len);
pt3[nCount][len] = '\0';
nCount++;
pt1 = pt1 + 1;
pt2 = pt1;
}
else
{
ret = -5;
printf("instr error:%d\n", ret);
/*return ret;*/
goto END;
}
}
else
{
ret = -6;
printf("NO ',' error:%d\n", ret);
/*return ret;*/
goto END;
}
} while (*pt1 != '\0');
END:
if (ret != 0)//失败
{
/*
if (pt3 == NULL)
{
return ret;
}
for (i = 0; i < nCount; i++)
{
if (pt3[i] != NULL)//已经分配内存了
{
free(pt3[i]);
}
}
if (pt3 != NULL)
{
free(pt3);
}*/
FreeMallocMem1(&pt3, nCount);
}
else
{
*p3 = pt3;
}
return ret;
}
void printArray1(char** p2, int num)
{
int i = 0;
for (i = 0; i < num; i++)
{
printf("%s\n", p2[i]);
}
}
int main()
{
int ret = 0;
char* str = "ab,co,12ad,error,good,";
int rows = 0;
char c = ',';
char** pt = NULL;
ret = Split_string(str, c, &pt, &rows);
if (ret != 0)
{
printf("func Split_string() error:%d\n", ret);
return ret;
}
//print
printArray1(pt, rows);
system("pause");
return 0;
}