0

What is wrong in the attached code sorting an array of strings using pointers

https://code.sololearn.com/c37Ix0HZjmPe/?ref=app

13th Feb 2022, 5:56 AM
Alddd
Alddd - avatar
4 Respostas
+ 2
The primary problem is that it is attempting to free an unallocated pointer, &names. It should free each of the pointers contained within names[]. Secondary, the print loop index goes out of bounds if list < 5. To solve both problems change from: for (int i = 0; i < 5; i++) printf("%s\n", names[i]); free(names); To: for (int i = 0; i < list; i++) { printf("%s\n", names[i]); free(names[i]); } I strongly recommend cleaning up the formatting of braces and indentation. Note: compareStr() could be directly replaced with the string library function strcmp().
13th Feb 2022, 4:40 PM
Brian
Brian - avatar
+ 2
thank you it worked
13th Feb 2022, 4:53 PM
Alddd
Alddd - avatar
0
Line 28 For loop condition should be i < list Then remove line 30 free(names)
13th Feb 2022, 7:06 AM
Raul Ramirez
Raul Ramirez - avatar
0
why shouldn't we use free as we are allocating memomory using malloc
13th Feb 2022, 7:08 AM
Alddd
Alddd - avatar