簡體   English   中英

在 C 中按字母順序排序指向字符的指針數組時出現分段錯誤

[英]Segmentation fault when alphabetically sorting an array of pointers to chars in C

假設我想按字典順序對數組**x進行排序,並且我正在嘗試使用排序:

char **x
    for (i = 0; i < sizeof(x); i++) {
        if (strcmp(x[i], x[i + 1]) > 0) {
           char *temp = x[i];
           x[i] = x[i + 1];
           x[i + 1] = temp;
        }
    }

當然,我也在遍歷它。 但是,每次我嘗試排序時,都會遇到分段錯誤。 當我不排序時,它打印得很好。 什么可能導致排序失敗?

如果不知道數組的大小,這將不起作用。 當您調用 sizeof(x) 時,實際上返回的是 sizeof(char**),它在大多數 64 位系統上為 8,而不是數組中的元素數。

您需要知道數組中元素的數量,然后修改代碼來執行此操作:

int x_length = <number of elements in x>
char **x
for (i = 0; i < x_length; i++) {
    if (strcmp(x[i], x[i + 1]) > 0) {
       char *temp = x[i];
       x[i] = x[i + 1];
       x[i + 1] = temp;
    }
}

暫無
暫無

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

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