而不是冒泡这些名称...程序崩溃

时间:2013-07-17 17:42:18

标签: c

我显然做错了什么,但是对于我的生活,无法弄清楚是什么。

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 the 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 they are:\n");
    for (i = 0; i < 5; i++)
    {
        printf("%s \n", names[i]);
    }

    system("PAUSE");
    return EXIT_SUCCESS;
 }

2 个答案:

答案 0 :(得分:3)

你有一个字符串文字数组。这些可能存放在只读存储器中,因此您无法更改其内容。但是,您可以通过替换

来更改在names中存储指针的顺序
strcpy(temp[0],names[i]);
strcpy(temp[1],names[i+1]);
strcpy(names[i],temp[1]);
strcpy(names[i+1],temp[0]);

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

答案 1 :(得分:0)

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

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

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

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

names字符串是字符串文字,字符串文字在C中是不可变的。尝试修改字符串文字会调用未定义的行为。