This is not actually C++ it is plain C and I need some clearance about why this is not working. This is a simple sorting mechanism that I am trying to implement. here is the code of my test program:
I'm trying to shift names as I compare them. The part with the realloc is not clear to me - I am acually using the gcc compiler and I know that this is a Visual C++ forum - but I thought that you can help guys.Code:#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXNUM 5 void sort_asc(char *, char *, int n); int main () { int a, b; char *f_names[MAXNUM]; char *l_names[MAXNUM]; char buf[80]; for (a = 0; a < MAXNUM; a++) { printf("\nFirst Name[%d]: ", a + 1); scanf("%s", buf); f_names[a] = (char *)malloc(sizeof(char) * strlen(buf)); strcpy(f_names[a], buf); printf("\tSecond Name[%d]: ", a + 1); scanf("%s", buf); l_names[a] = (char *)malloc(sizeof(char) * strlen(buf)); strcpy(l_names[a], buf); } printf("Sorting ...\n"); sort_asc(f_names[a], l_names[a], MAXNUM); printf("\nFinished Sorting! Displaying results:"); for (a = 0; a < MAXNUM; a++) printf("\nName[%d]: %s %s\n", a + 1, f_names[a], l_names[a]); return 0; } void sort_asc(char *fn, char *ln, int n) { char *temp; int a, b, c, len; for (a = 0; a <= n; a ++) for (b = 0; b < n; b++) { c = strcmp((const char *)fn[b], (const char *)fn[b + 1]); if (c > 0) { temp = (char *)malloc(sizeof(char) * strlen((const char *)fn[b])); strcpy(temp, (const char *)fn[b]); len = strlen((const char *)fn[b + 1]); fn[b] = (char *)realloc(fn[b], sizeof(char) * len); strcpy(fn[b], fn[b + 1]); fn[b + 1] = (char *)realloc(fn[b + 1], sizeof(char) * strlen((const char *)temp)); strcpy(fn[b + 1], (const char *)temp); } } }
Thanks anyway.
The_Prince




Reply With Quote