c - Can't more than two strings compare? -


if compared integers assign 1 of them largest/smallest one. however, when try comparing more 2 strings, can't manage assaigment. in code "for loop" compares 2 of strings. method need compare 1 of them others individually. (i can predict need use 2 loop, can't implement) suggestions?

here code:

#include <stdio.h> #include <stdlib.h> #include <string.h>  typedef struct wordsorting {     char name[15];     int = 0; };  int main() {     wordsorting *wordelement = (wordsorting *)malloc(sizeof(wordsorting));     wordelement = (wordsorting *)malloc(sizeof(wordsorting));      printf("-- enter 3 person name --\n\n");     (wordelement->i = 0; wordelement->i < 3; wordelement->i++)     {         printf("enter %d. person name: ", wordelement->i + 1);         scanf("%s", wordelement[wordelement->i].name);     }     printf("\n");      (wordelement->i = 0; wordelement->i < 3; wordelement->i++)     {         if ((strcmp(wordelement[wordelement->i].name, wordelement[wordelement->i + 1].name))<0)         {             printf("%s", wordelement[wordelement->i].name);         }     } } 

first

typedef struct wordsorting {     char name[15];     int = 0; }; 

members of typedef/struct cannot initied. not way define typedef, change as:

typedef struct {     char name[15];     int i; }wordsorting; 

second:

wordelement = (wordsorting *)malloc(sizeof(wordsorting));   

makes no sense. malloc returns void pointer, , init variable @ first element in first line of code. and, edited: not cast malloc return, please.

third, :

wordsorting *wordelement = (wordsorting *)malloc(sizeof(wordsorting)); wordelement = (wordsorting *)malloc(sizeof(wordsorting));  printf("-- enter 3 person name --\n\n"); (wordelement->i = 0; wordelement->i < 3; wordelement->i++) {     printf("enter %d. person name: ", wordelement->i + 1);     scanf("%s", wordelement[wordelement->i].name); } 

you allocating space 1 element, no array defined wordelement[wordelement->i].name undefined behaviour.

finally

i don't know compiler using, gcc cannot compile such bad code full of errors...

suggestion.

what think need use array, must allocate number of member need, by:

wordsorting *wordelement = malloc(sizeof(wordsorting)*num_of_elements); 

or simply, using local array:

wordsorting wordelement[num_of_elements]; 

Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -