程序的功能:在主函數中通過二維數組和指針的定義的字符串,在被調用函數中分配動態內存,並排序。
一、在主函數定義二維數組和指針數組,並初始化
int main(void)
{
char *p[] = { "11111", "22222", "33333" };
char str[][6] = { "aaaaa", "bbbbb", "ccccc" };
char **p1 = NULL;
int len1, len2, len3;
len1 = sizeof(p)/sizeof(*p);
len2 = 3;
int ret = sort(p, len1, str, len2, &p1, &len3);
for (int i = 0; i < len3; i++)
{
cout << p1[i] << endl;
}
free2(&p1, len3);//調用自定義的釋放內存函數
return 0; system("pause"); }
二、被調用函數。在主函數的用的二級指針定義的字符串,那麼在被調用函數中用三級指針接過來,先要在堆中動態分配一個二維的(len1+len2)大小的指針長度的內存,在分別分配len1大小的內存用來放字符串1的數據和len2大小的內存用來存字符串2的數據。對所有存入的數據進行排序。
int sort(char **p, int len1, char (*str)[6], int len2, char ***p1, int *len3)
{
char** tempP = (char**)malloc(sizeof(char*)*(len1 + len2));
if (tempP == NULL)
{
return -1;
}
int i = 0;
int strLen = 0;
for (; i < len1; i++)
{
strLen = strlen(p[i]) + 1;
tempP[i] = (char*)malloc(sizeof(strLen));
if (tempP[i] == NULL)
{
return -2;
}
strcpy(tempP[i], p[i]);
}
for (int j = 0; j < len2; j++,i++)
{
strLen = strlen(str[j]) + 1;
tempP[i] = (char*)malloc(sizeof(strLen));
if (tempP[i] == NULL)
{
return -3;
}
strcpy(tempP[i], str[j]);
}
//排序
strLen = len1 + len2;
char *myp = NULL;
for (int x = 0; x < strLen; x++)
{
for (int y = x+1; y < strLen; y++)
{
if (strcmp(tempP[x], tempP[y])>0)
{
//交換指針指向,也可以用交換內容
myp = tempP[x];
tempP[x] = tempP[y];
tempP[y] = myp;
}
}
}
*len3 = strLen;
*p1 = tempP;
return 0;
}
三、分配了動態內存那麼就要釋放內存。在主函數中調用釋放內存的函數,釋放內存函數如下:
void free2(char ***myp, int len)
{
char **p = NULL;
if (myp == NULL)
{
return;
}
p = *myp;//還原成二級指針
if (p == NULL)
{
return;
}
for (int i = 0; i < len; i++)
{
free(p[i]);
}
free(p);
*myp = NULL;
}
但是每次程序調用釋放內存函數都會出現問題,程序會停在這個函數中。輸出結果:

不知道是什麼原因導致的,如果有大神知道還望指導一下。
編譯環境:win7+VS2013