C-实现strcpy()但是Segfault



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

#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("%sn", dest[i][20]);
}
return 0;
}

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

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

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

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

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

  • 在打印循环中CCD_ 10是指第CCD_。您应该将字符串作为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("%sn", dest[i]);
}
return 0;
}

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

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

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

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

printf("%sn", dest[i][20]);

相关内容

最新更新