Search code examples
cbubble-sort

Bubble sorting an array of strings in C


I've been trying to bubble sort an array of strings but I always get the "Segmentation fault" Error. Any help is appreciated.

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

int main()
{
char *arreglo[20]={"Ruben","Modesta","Jan","Ana","Amparo","Josu","Azahara","Concepcio","Carmelo","Miguel","Francesc","Jairo","Jose","Luis","Teo","Jone","Jacobo","Ainoa","Natalia","Igor"};
int i;
int j;
char *temp;


for (int j=0; j<20; j++) 
{ 
    for (int i=j+1; i<20; i++) 
    { 
        if (strcmp(arreglo[j], arreglo[i]) > 0) 
        { 
            strcpy(temp, arreglo[j]); 
            strcpy(arreglo[j], arreglo[i]); 
            strcpy(arreglo[i], temp); 
        } 
    } 
} 

}


Solution

  • String literals are typically stored in read-only memory area, not intended to be modified.

    In this question, there is no need to move the string literal. Instead, we can just modify the string pointers. It's faster and safer.

    Please check this code:

        #include <stdio.h>
        #include <stdlib.h>
        #include <string.h>
    
        int main()
        {
            const char *arreglo[20]={"Ruben","Modesta","Jan","Ana","Amparo","Josu","Azahara","Concepcio","Carmelo","Miguel","Francesc","Jairo","Jose","Luis","Teo","Jone","Jacobo","Ainoa","Natalia","Igor"};
            int i;
            int j;
            const char *sorted[20];
    
            for(i=0;i<20;i++){
                sorted[i] = arreglo[i];
            }
    
            for (j=0; j<20; j++){
                for (i=j+1; i<20; i++) {
                    if (strcmp(sorted[j], sorted[i]) > 0) {
                        const char *temp = sorted[j];
                        sorted[j] = sorted[i];
                        sorted[i] = temp;
                    }
                }
            }
            for(i=0;i<20;i++){
                printf("%d:%s\n",i,sorted[i]);
            }
        }
    

    Pointers points to string literals are set to "const char *"

    Hopefully this may help you solve your problem.