简体   繁体   中英

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM