北城已荒凉 2018-10-30 04:16 采纳率: 0%
浏览 266

我试图编写一个 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

  • 写回答

2条回答 默认 最新

  • bug^君 2018-10-30 04:32
    关注

    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");
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?