![
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **create_memory(int num)//分配内存
{
int i = 0;
char **p1 = NULL;
p1 = (char**)malloc(sizeof(char*)*num);
if (p1 == NULL)
{
return NULL;
}
for (i = 0; i < num; i++)
{
p1[i] = (char*)malloc(sizeof(char) * 100);
}
return p1;
}
int count_string(char *str)//判断能分成几个字符串
{
int count = 0;
if (str == NULL)
{
return -1;
}
while (*str != '\0')
{
if (*str == ',')
{
count++;
}
str++;
}
return count + 1;
}
int split_string(char *str_old, char **str_new, int *length)//拆分字符串
{
int ret = 0;
if (str_old == NULL || str_new == NULL || length == NULL)
{
return -1;
}
int count = 1;
int i = 0;
char *tmp = str_old;
while (*tmp != '\0')//将逗号全部替换为\0
{
if (*tmp == ',')
{
*tmp = '\0';
count++;
}
tmp++;
}
*length = count;
for (i = 0; i < count; i++)
{
str_new[i] = str_old;
while (*str_old++ != '\0');
}
return ret;
}
void free_all(char **p1, int num)
{
int i = 0;
for (i = 0; i < num; i++)
{
if (*(p1 + i) != NULL)
{
free(*(p1+i));
*(p1 + i) = NULL;
}
}
if (p1 != NULL)
{
free(p1);
}
}
int printf_all(char **p1, int num)
{
int ret = 0;
if (p1 == NULL)
{
return -1;
}
int i = 0;
for (i = 0; i < num; i++)
{
printf("%s\n", p1[i]);
}
return ret;
}
void main()
{
int ret = 0;
char str[100] = "abcdef,ghijk,lmno,pqrst,aaaaaa";
int length = 0;
int num = 0;
num = count_string(str);//num=传输出的二级指针行数
if (num < 0)
{
printf("ERROR!!! function:count_string()%d", num);
return;
}
char **p1 = NULL;
p1 = create_memory(num);//分配内存
if (p1 == NULL)
{
printf("ERROR!!! function:create_memory()");
return;
}
ret = split_string(str, p1, &length);//拆分函数
if (ret != 0)
{
printf("ERROR!!! function:split_string()");
return;
}
printf("%d\n", length);//打印行数
ret=printf_all(p1, num);// 打印
if (ret != 0)
{
printf("ERROR!!! function:printf_all()");
return;
}
free_all(p1, num);// 释放内存,问题就出在这
system("pause");
}
图片说明](https://img-ask.csdn.net/upload/201606/08/1465357699_863906.png)