簡體   English   中英

而不是冒充這些名稱...程序崩潰

[英]Rather than bubblesorting these names…the program crashes

我顯然做錯了,但是,對於我自己的一生,無法弄清楚是什么。

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

您有一個字符串文字數組。 它們可能被保存在只讀存儲器中,因此您不能更改其內容。 但是,您可以通過替換來更改將指針存儲在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;
       strcpy(temp[0],names[i]);

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

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

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

names字符串是字符串文字,字符串文字在C中是不可變的。嘗試修改字符串文字會導致未定義的行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM