我试图编写一个 c 代码来对 String 进行排序,但是在第13行总是显示一个错误消息

I'm trying to write a C code to sort strings, but there always shows an error message in line 13.

#include <stdio.h>
#include <string.h>

void SortString(char *strings[], int size)
{
    char temp[10];
    for(int i =0; i < size -1; i++)
        for(int j = i+1; j<size; j++)
        {
            if (strcmp(strings[i], strings[j])>0)
            {
                strcpy(temp, strings[i]);
                strcpy(strings[i], strings[j]); //Error: Thread 1: EXC_BAD_ACCESS (code=2, address=0x100000fa6)
               strcpy(strings[j], temp);
           }
       }    }
   int main(){
   char *names[] = {"D", "C", "B", "A"};
   SortString(names, 4);    }

I know I can change *name[]into name[][20] and change void SortString(char *strings[], int size) to void SortString(char strings[][20], int size) to make the code correct, but why *name[] is wrong?

转载于:https://stackoverflow.com/questions/53057327/im-trying-to-write-a-c-code-to-sort-string-but-there-always-shows-an-error-mes

I am referring to this page.

char *names[] = {"D", "C", "B", "A"};

When you declare strings like this, they will be present in a read-only memory. You are trying to modify the content of the memory in your function and that is why you are getting the error.

Best way to achieve this functionality is to allocate memory for each member of the names array and then initialize it.

There are many ways to do it. I have given an example below.

char **names = malloc(MAX_ARRAY_SIZE * sizeof(char*));
if(NULL == names) {/**/}

names[0] = malloc(strlen("D")+1); //+1 for '\0' at the end.
if(NULL == names[0]) {/* Handle it*/}
strcpy(names[0], "D");

The data you're sorting is an array of char *, pointers to character strings. To reorder the array you just need to swap the pointers. You don't need to move the string contents. In fact you can't move the string contents in this case because they are string literals. You get a segfault when you try to write to read-only values.

I've slightly rewritten your function to just swap pointers and it seems to work now.

void SortString(char *strings[], int size)
{
    char *temp;
    for(int i = 0; i < size - 1; i++) {
        for(int j = i + 1; j < size; j++) {
            if (strcmp(strings[i], strings[j]) > 0) {
                temp = strings[i];
                strings[i] = strings[j];
                strings[j] = temp;
            }
        }
    }
}

Live demo on Ideone.com