简体   繁体   English

在 C 中按字母顺序排序指向字符的指针数组时出现分段错误

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

Say I want to lexicographically sort an array, **x , and I'm attempting to use an sort:假设我想按字典顺序对数组**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;
        }
    }

Of course, I'm also looping through it too.当然,我也在遍历它。 Each time I attempt to sort, however, I get a segmentation fault.但是,每次我尝试排序时,都会遇到分段错误。 It prints fine when I don't sort it.当我不排序时,它打印得很好。 What could be causing the sort to fail?什么可能导致排序失败?

This will not work without knowing the size of the array.如果不知道数组的大小,这将不起作用。 When you call sizeof(x) you are in fact returning sizeof(char**) which is 8 on most 64 bit systems and NOT the number of elements in the array.当您调用 sizeof(x) 时,实际上返回的是 sizeof(char**),它在大多数 64 位系统上为 8,而不是数组中的元素数。

You need to know the number of elements in the array and than modify you code to do this:您需要知道数组中元素的数量,然后修改代码来执行此操作:

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