【问题标题】:C -Implementing strcpy() But SegfaultC - 实现 strcpy() 但 Segfault
【发布时间】:2021-08-12 03:43:58
【问题描述】:

我做了一个strcpy() 函数 在 C 中,我将单词从一个数组复制到另一个数组,而不仅仅是字母,但是当我运行它时,我遇到了 Segmentation fault 该怎么办?

#include <stdio.h>

void strcpy1(char *dest[], char source[])
{
    while ((*dest++ = *source++));
}

int main()
{
    char source[3][20] = { "I", "made", "this" };
    char dest[3][20];

    strcpy1(&dest, source);
    
    //printing destination array contents   
    for (int i = 0; i < 3; i++) {
        printf("%s\n", dest[i][20]);
    }

    return 0;
}

【问题讨论】:

    标签: c string segmentation-fault char strcpy


    【解决方案1】:

    %s 说明符用于字符串,例如,char* 指代字符串的第一个字符。

    当您将dest[i][20] 传递给printf 函数时,它不是char*。它是单个char21st char(有效索引为0-19,共20 个元素)。

    所以它是一个数组越界索引,也不是printf 所期望的char*

    printf("%s\n", dest[i][20]);
    

    【讨论】:

      【解决方案2】:

      您的代码中存在多个问题:

      • 您的自定义 strcpy1 函数的原型应该是:

        void strcpy1(char *dest[], char *source[]);
        
      • 数组sourcedest 是二维char 数组:与strcpy1 所期望的类型非常不同,它们是指针数组。将定义更改为:

         char *source[4] = { "I", "made", "this" };
         char *dest[4];
        
      • 您应该将目标数组传递为dest 而不是&amp;dest

      • 源数组应该有一个 NULL 指针终止符:它应该定义为长度至少为 4。目标数组也是如此。

      • 在打印循环中dest[i][20] 指的是超出i-th 字符串结尾的字符。您应该将字符串作为dest[i] 传递。

      这是修改后的版本:

      #include <stdio.h>
      
      void strcpy1(char *dest[], char *source[])
      {
          while ((*dest++ = *source++));
      }
      
      int main()
      {
          char *source[4] = { "I", "made", "this" };
          char *dest[4];
      
          strcpy1(dest, source);
          
          //printing destination array contents   
          for (int i = 0; dest[i]; i++) {
              printf("%s\n", dest[i]);
          }
      
          return 0;
      }
      

      请注意,将 strcpy1 命名为与标准函数 strcpy() 具有非常不同语义的函数有点令人困惑。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-06
        • 2013-10-18
        • 2013-07-28
        • 1970-01-01
        • 2017-08-08
        • 1970-01-01
        • 2020-10-11
        • 2015-03-19
        相关资源
        最近更新 更多