[英]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.