繁体   English   中英

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

[英]I got issue in strcpy in C, is there any mistake in my code?

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

我试图在 C 中学习string.h ,将做strcpy我无法获得 output。 output 就像

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 数组,因此它使用字符串“Bye”的大小进行了初始化,该大小小于字符串“Hello”。 这就是问题发生的原因。

解决方案:

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

int main() 
{
    char oldS[6] = "Hello";
    char newS[6] = "Bye";
    strcpy(newS, oldS);
    puts(newS);
}

您需要分配空间以使用 strcpy 创建具有足够大小的数组或使用malloc

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM