-1
#include<stdio.h>
#include<string.h>
int main(){
    char *a[]={"this","is","a","string"};
    char temp[100];
    for(int i=0;i<3;i++){                               
        for(int j=0;j<3-i;j++){
            if(strcmp(a[j],a[j+1])>0){
                strcpy(temp,a[j]);
                strcpy(a[j],a[j+1]);
                strcpy(a[j+1],temp);
            }
        }
    }
    for(int i=0;i<4;i++){
        printf("%s\n",a[i]);
    }
}

The following code is for bubble sorting the strings.It gives segmentation fault.What is wrong in it?

Vedant
  • 27
  • 3

2 Answers2

3

String literals are read-only in C. Your strcpy(a[j],a[j+1]) and strcpy(a[j+1], temp) calls are illegal.

Navneeth
  • 373
  • 3
  • 15
3

There is no need to use strcpy. The only thing that you have to do is to swap a[j] and a[j+1] pointers.

Make sure that the for loop have the correct bounds. The array has size 4, and valid elements are in the range [0..4)

Take a look at the following:

int main(){
        char const *a[]={"this","is","a","string"}; //const added
        char *temp = 0; // a simple pointer
        for(int i=0;i<4;i++){     //bounds changed                          
                for(int j=0;j<4-1;j++){
                        if(strcmp(a[j],a[j+1])>0){ // swap pointers
                            temp = a[j];
                            a[j] = a[j+1];
                            a[j+1]=temp;
                        }
                }
        }
        for(int i=0;i<4;i++){
                printf("%s\n",a[i]);
        }
}
Davide Spataro
  • 7,319
  • 1
  • 24
  • 36
  • Why is using strcpy() not allowed? – Vedant Feb 20 '18 at 13:06
  • Take a look at the following. https://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string-initialized-with-cha . Please be aware that avoiding `strcpy` altogether translates to a much more efficient function. – Davide Spataro Feb 20 '18 at 13:08
  • Im sorry, that was meant to be 3-i and not 3-1. – Vedant Feb 20 '18 at 13:12