0

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

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;
 }
4

2 回答 2

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;
于 2013-07-17T17:44:41.573 回答
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 中是不可变的。尝试修改字符串文字会调用未定义的行为。

于 2013-07-17T17:43:54.120 回答