微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C - 实现 strcpy() 但段错误

如何解决C - 实现 strcpy() 但段错误

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

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

解决方法

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

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

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

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

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

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

这是修改后的版本:

#include <stdio.h>

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

int main()
{
    char *source[4] = { "I","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() 非常不同的语义的函数有些令人困惑。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。