C : Array of strings - Can input only n-1 strings for an input size of n -
i have sort strings in lexicographical order using bubble sort technique without using library functions. have written following code working fine in sorting strings.
problem if give n input (say n = 4), can enter n-1 strings (only 3 strings). problem can solved running loops 0 n, isn't logical solution.
doing wrong here?
#include <stdio.h> #include <string.h> #include <malloc.h> void swap(int indx[], int j) { int temp; temp = indx[j]; indx[j] = indx[j+1]; indx[j+1] = temp; } void sort(char **str, int indx[], int n) { int i, j, k; for(i=0; i<n; i++) { for(j=0; j<n-i-1; j++) { k = 0; while(str[j][k] != '\0') { if((str[indx[j]][k]) > (str[indx[j+1]][k])) { swap(indx, j); break; } else if((str[indx[j]][k]) < (str[indx[j+1]][k])) break; else k++; } } } } void display(char **str, int indx[], int n) { int i; printf("sorted strings : "); for(i=0; i<n; i++) printf("%s\n", str[indx[i]]); } int main(void) { char **str; int n, i, j, *indx; printf("enter no. of strings : "); scanf("%d", &n); str = (char **) malloc (n * (sizeof(char *))); indx = (int *) malloc (n * sizeof(int)); for(i=0; i<n; i++) str[i] = (char *)malloc(10 * sizeof(char)); printf("enter strings : "); for(i=0; i<n; i++) { gets(str[i]); indx[i] = i; } sort(str, indx, n); display(str, indx, n); }
the problem use of scanf()
. when scanf("%d", &n)
, scanf()
function reads input until finds integer, , puts value n
. however, when entered integer, didn't type '4', typed '4' , pressed enter. , newline still in input buffer. gets()
function, on other hand, reads input and including first newline, , newline character discarded. when you're reading input strings, gets call gets()
reads newline, , returns immediately. , then, first string enter read second call gets()
...
incidentally, gets()
function should never, ever, under circumstances, ever used real programs, because doesn't allow limit input. better use fgets()
. fgets(str[i], buffersize-1, stdin)
.
Comments
Post a Comment