我在C中的strcpy中遇到了问题,我的代码中有错误吗


#include<stdio.h>
#include<string.h>
int main() {
char oldS[] = "Hello";
char newS[] = "Bye";
strcpy(newS, oldS);
puts(newS);
}

我试图在C中学习string.h,将要做strcpy我无法获得输出。输出类似

koushik@Koushiks-MacBook-Air C % cd "/Users/koushik/Documents/
C/" && gcc stringcopy.c -o stringcopy && "/Users/koushik/Docum
ents/C/"stringcopy
zsh: illegal hardware instruction "/Users/koushik/Documents/C/"stringcopy

使用strcpy()时,目标字符串的大小应该足够大,可以存储复制的字符串。否则,可能会导致未定义的行为。

正如您在没有指定大小的情况下声明了char数组一样,它是用字符串"的大小初始化的;再见";,其小于字符串";你好;。这就是问题发生的原因。

解决方案:

#include<stdio.h>
#include<string.h>
int main() 
{
char oldS[6] = "Hello";
char newS[6] = "Bye";
strcpy(newS, oldS);
puts(newS);
}

您需要分配空间来使用strcpy,无论是创建具有后缀大小的数组,还是使用malloc

最新更新