#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TRUE 1
#define FALSE 0
#define BUFFER_LEN 240
#define NUM_P 50

void str_sort (char *[], int); 

int main ()
{
  char *s[NUM_P]; 
  int count; 
  printf("Enter the number of count:");
  scanf("%d",&count); 
  int i = 0; 

  printf("enter the first string:"); 
  scanf("%s",&s[0]);
  printf("enter the second string:"); 
  scanf("%s",&s[1]);
  printf("enter the third string:"); 
  scanf("%s",&s[2]);
  printf("enter the fourth string:"); 
  scanf("%s",&s[3]);
  printf("enter the fifth string:"); 
  scanf("%s",&s[4]);

  str_sort (s, count);
  
  printf("\n the sorted output is: \n \n");
  for (i =0; i <count; i ++)
  {
   printf("%s \n", s[i]);
   free(s[i]);
   s[i] = NULL; 
  }
}

void str_sort (char *p[], int n)
{
 char *pTemp = NULL; 
 int i = 0; 
 int sorted = FALSE; 
 while (!sorted)
 {
  sorted = TRUE; 
  for (i = 0; i <n-1; i++)
   if (strcmp(p[i], p[i+1]) > 0)
   {
    sorted = FALSE; 
    pTemp = p[i]; 
    p[i] = p[i+1];
    p[i+1] = pTemp; 
   }
 }
}

the program stops executing exactly after the 5th scanf statement .. please do help .. thanks :)

Recommended Answers

All 3 Replies

Consider only this:

scanf("%s", &s[0]);
printf("%s", s[0]);

What happens?

Also, you are free()-ing something you haven't allocated. If you know how many strings you need, I recommend using an array of strings. Here's a working sample for you.

#include <stdio.h>
#define BUFFER_LEN 240
#define NUM_P 50
void printsample(char *[][]);
int main()
{
    char s[NUM_P][BUFFER_LEN];
    fgets(&s[0], BUFFER_LEN, stdin);
    printsample(&s);

    return 0;
}

void printsample(char *p[NUM_P][BUFFER_LEN])
{
  printf("%s", p[0]);
}

Thanks a bunch strmstn .. ur sample example really helped and finally got my program to work .. thanks again for ur quick reply :) i really appreciate it ..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.