CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Mar 2006
    Posts
    1

    C sorting problem

    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:
    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);
    	  }
          }
    }
    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.

    Thanks anyway.

    The_Prince
    Last edited by Ejaz; March 15th, 2006 at 01:09 AM. Reason: Code tag added

  2. #2
    Join Date
    Jun 2005
    Location
    Tirunelveli-Tamil Nadu-India
    Posts
    354

    Thumbs up Re: C sorting problem

    Code:
    sort_asc(f_names[a], l_names[a], MAXNUM);
    the above code f_names[a] is null nothing is there. debug the program. check ur for loop in ur main function.
    If I Helped You, "Rate This Post"

    Thanks
    Guna

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured