c - 如何修复此错误以及为什么会出现此错误?

标签 c

我需要将 12 小时格式的时间转换为 24 小时格式。

我现在对 12 小时的时间进行了硬编码,以使事情变得更简单。

我的逻辑: 输入刺 07:05:45PM 提取最后 2 个字符。 如果上午 检查前 2 个字符是否为 12。如果是,则将其改为 00 否则按原样输出 如果下午 检查前 2 位数字是否为 12 ..如果是,则保持原样 如果不是,则将 12 添加到前 2 位数字

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

    char* timeConversion(char* s1)
    {
        // input sting 07:05:45PM
        // extract last 2 chars.
        // if AM 
        // check is first 2 chars are 12.. if yes chance them to 00
        // else output as it is
        // if PM 
        // check if first 2 digits are 12 ..if yes leave as it is
        // if not then add 12 to first 2 digits

        char s[strlen(s1) + 1];
        strcpy(s, s1);


        char suffix[3]; // pm am 
        suffix[0] = s[strlen(s) - 2];
        suffix[1] = s[strlen(s) - 1];
        suffix[2] = '\0';

        char xx[3]; // first 2 nos
        xx[0] = s[0];
        xx[1] = s[1];
        xx[2] = '\0';

        s[strlen(s1) - 1] = '\0';
        s[strlen(s1) - 2] = '\0';

         if(strcmp(suffix, "AM") == 0)
        {
            if(strcmp(xx, "12") == 0)
            {
                s[0] = '0';
                s[1] = '0';
                strcpy(s1, s);

             }
             else
            {
                return s1;
            }
        }
        else
        {


            if(strcmp(xx, "12") == 0)
            {
                strcpy(s, s1);
                return s1;
             }
            else
            {
                int n;
                // 01 - 09 
                if(xx[0] == '0')
                {
                    char x = xx[1];
                    n = x - '0';

                    // xx = itoa(n);
                }
                else
                {
                    // 10, 11
                    n = atoi(xx);

                }
                n = n + 12;



                 // itoa(n, xx, 10);
                sprintf(xx, "%d", n); 
                s[0] = xx[0];
                s[1] = xx[1];
            }
        }
        strcpy(s1, s);
        return s1;   
    }  

    int main()
    {
       char *str = "07:05:45PM";
       char *str1 = timeConversion(str);
       printf("%s\n", str1);
       return 0;

    }

总线错误:10 是我运行代码时遇到的问题

最佳答案

问题出在

 strcpy(s1, s);

您实际上是在尝试写入指向字符串文字的第一个元素的指针。它调用undefined behaviour .

检查函数调用

timeConversion(str);

其中 str 指向字符串文字,并且任何修改字符串文字内容的尝试都是 UB。

您需要在 timeConversion() 函数中执行以下操作:

  • 已分配所需的内存量(调用 malloc() 是一种方法)
  • 用它来保存修改后的输出
  • 将指针返回给调用者。
  • 使用完内存后将其释放。

关于c - 如何修复此错误以及为什么会出现此错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56234057/

相关文章:

c - 为什么C和C++中signed char的范围不同?

c - C 中的按位移位

c - 需要帮助来理解数组

c - 写入和读取文件的问题

我可以将 NULL 传递给 modf/modff 吗?

c - sprintf 段错误而 printf 正常

c++ - C(++) 对未存储在变量中的值有什么作用?

c++ - 为什么我们需要 argc 而 argv 的末尾总是有一个空值?

c - 每个客户端服务器一个进程在 C 中使用共享内存

c - 在c中使用管道实现简单的shell?