1 / 3
Oct 2008

hello all. I've writen a piece of code which reads strings with gets() function and tries to sort them with qsort( it just tries , it can't =) )

here is my code , what is the problem ?

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int cstring_cmp(const void *a, const void *b)
{
	return strcmp(*(char **)a, *(char **)b);
}
int main() {
	char bank_accounts[100][32];
	int t;
	int n;
	int i;
	scanf("%d",&t);
	while(t--) {
		scanf("%d\n",&n);
		for(i=0;i<n;++i)
		{
			gets(bank_accounts[i]);
			bank_accounts[i][31]='\0';
		}
    	for(i=0;i<n;++i)
		printf("-%s-\n",bank_accounts[i]);
	qsort(bank_accounts,n,sizeof(char *),cstring_cmp);
	
}
return 0;
}

thank you all

  • created

    Oct '08
  • last reply

    Oct '08
  • 2

    replies

  • 1.3k

    views

  • 2

    users

  • 1

    link

char a[] and char * are not the same.See here18.

Here is your modified code:

#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int cstring_cmp(const void *a, const void *b)
{
   return strcmp(*(char **)a, *(char **)b);
}
int main() {
   char *bank_accounts[100];	// char * , not char[]
   int t;
   int n;
   int i;
   scanf("%d",&t);
   while(t--) {
      scanf("%d\n",&n);
      for(i=0;i<n;++i)
      {
		 bank_accounts[i]=(char *)malloc(33);	// allocate memory
         gets(bank_accounts[i]);
         bank_accounts[i][31]='\0';
      }
      for(i=0;i<n;++i)
     printf("-%s-\n",bank_accounts[i]);
  qsort(bank_accounts,n,sizeof(char *),cstring_cmp);
   }
   return 0;
}

Suggested Topics

Topic Category Replies Views Activity
C and C++ 0 34 26d

Want to read more? Browse other topics in C and C++ or view latest topics.