c - Rather than bubblesorting these names...the program crashes -


i doing wrong but, life of me, can't figure out what.

int main(int argc, char *argv[]) {     int done=0;     int end=0;     int didswap=0;     char *temp[2] = {0};     int i;     int x;     printf("this function bubble sorts flintstones in alphabetical order!\n");     printf("the flintstones names are:\nfred\nbarney\nwilma\npebbles\ndino\n");     char *names[5] = {0};     names [0] = "fred";     names [1] = "barney";     names [2] = "wilma";     names [3] = "pebbles";     names [4] = "dino";     while(end == 0)     {         for(i=0;i<4;i++)         {              if (strcmp(names[i],names[i+1])>0)             {                 strcpy(temp[0],names[i]);                 strcpy(temp[1],names[i+1]);                 strcpy(names[i],temp[1]);                 strcpy(names[i+1],temp[0]);                 didswap = 1;             }             else             {                 didswap = 0;             }             done = done+didswap;         }           if (done == 0)             end = 1;         else             done = 0;     }     printf("when alphabetized are:\n");     (i = 0; < 5; i++)     {         printf("%s \n", names[i]);     }      system("pause");     return exit_success;  } 

you have array of string literals. these may held in read memory can't change content. can change order store pointers them in names replacing

strcpy(temp[0],names[i]); strcpy(temp[1],names[i+1]); strcpy(names[i],temp[1]); strcpy(names[i+1],temp[0]); 

with

const char* tmp = names[i]; names[i] = names[i+1]; names[i+1] = tmp; 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -