[C language basics] allocate memory in the pointer array defined by the main function and two-dimensional array through a third-level pointer in the called function,
Function of the program: in the main function, allocate dynamic memory and sort it in the called function through two-dimensional arrays and pointer-defined strings.
1. Define two-dimensional arrays and pointer arrays in the main function and initialize
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); // call a custom memory release function
Return 0; system ("pause ");}
2. Called functions. In the string defined by the second-level pointer of the main function, a two-dimensional (len1 + len2) must be dynamically allocated in the heap before being taken over by a third-level pointer in the called function) the size of the pointer length memory, respectively allocated len1 memory for storing string 1 data and len2 memory for storing string 2 data. Sort all stored data.
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]);} // sort 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) {// exchange pointer pointing, or use the exchanged content myp = tempP [x]; tempP [x] = tempP [y]; tempP [y] = myp ;}}} * len3 = strLen; * p1 = tempP; return 0 ;}
3. If dynamic memory is allocated, the memory will be released. Call the function to release the memory in the main function. The function to release the memory is as follows:
Void free2 (char *** myp, int len) {char *** p = NULL; if (myp = NULL) {return;} p = * myp; // restore to second-level pointer if (p = NULL) {return ;}for (int I = 0; I <len; I ++) {free (p [I]);} free (p); * myp = NULL ;}
But every time the program calls the function to release the memory, the program will stop in this function. Output result:
I don't know what causes it. If you have any idea, I 'd like to give you some guidance.
Compiling environment: win7 + VS2013