c语言多级指针怎么理解,c语言之多级指针理解二

通过字符分离的demo进行理解:

//释放内存空间

void FreeAllMemory(char*** toArry, int cnt){

if (toArry == NULL)

return;

char** tmpArry = NULL;

tmpArry = *toArry;

for (int i = 0; i < cnt; i++){

if (tmpArry[i] != NULL)

{

free(tmpArry[i]);

}

}

if (tmpArry != NULL){

free(tmpArry);

}

*toArry = NULL;

}

//输出数据

void PrintPData(char** str, int cnt){

if (str == NULL)

return;

for (int i = 0; i < cnt; i++){

printf_s("%s\n", *(str + i));

}

}

#pragma warning(disable:4996)//屏蔽安全检测

//分离字符串

void SplitStrByStr(char* sources, char str, char*** toArry, int* line){

//没有分配内存空间 直接返回

if (toArry == NULL){

return;

}

//行数

int tmpLine = 0;

char** tmpArry = NULL; //用于存储分配的内存空间 也就是toArry指向的内存空间

char* sourcesCp1 = NULL;

char* sourcesCp2 = NULL;

sourcesCp1 = sources;

sourcesCp2 = sources;

//查找需要分配的内存块个数 避免申请的内存空间没有用上 合理利用内存

do{

sourcesCp1 = strchr(sourcesCp1, str);

if (sourcesCp1 != NULL){

tmpLine++;

sourcesCp1++;

sourcesCp2 = sourcesCp1;

}

} while (*sourcesCp1 != '\0');

//分配内存空间

tmpArry = (char**)malloc(sizeof(char*)*tmpLine);

if (tmpArry == NULL)

return;

sourcesCp1 = sources;

sourcesCp2 = sources;

tmpLine = 0;

//分配具体数据的内存空间 合理利用空间

do

{

sourcesCp1 = strchr(sourcesCp1, str);

if (sourcesCp1 != NULL){

//两个字符指针的间隔

if (sourcesCp1 - sourcesCp2 > 0){

int len = sourcesCp1 - sourcesCp2 + 1;

tmpArry[tmpLine] = (char*)malloc(sizeof(char)*len);

if (tmpArry[tmpLine] == NULL){

FreeAllMemory(&tmpArry, tmpLine);

return;

}

//拷贝数据

strncpy(tmpArry[tmpLine], sourcesCp2, len - 1);

tmpArry[tmpLine][sourcesCp1 - sourcesCp2] = '\0';

tmpLine++;

sourcesCp1++;

sourcesCp2 = sourcesCp1;

}

}

} while (*sourcesCp1 != '\0');

*line = tmpLine;

*toArry = tmpArry;

}

void main(){

int line = 0;

char* pStr = "Rose_Girl1,Rose_Girl2,Rose_Girl3,Rose_Girl4,Rose_Girl5,";

char tmpChar = ',';

char** pArry = NULL;

SplitStrByStr(pStr, tmpChar, &pArry, &line);

PrintPData(pArry, line);

system("pause");

}

你可能感兴趣的:(c语言多级指针怎么理解)