Reputation: 1
#include<stdio.h>
#include<string.h>
int main() {
char oldS[] = "Hello";
char newS[] = "Bye";
strcpy(newS, oldS);
puts(newS);
}
I was trying to learn string.h
in C, will doing strcpy
I am unable to get the output.
output is like
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
Upvotes: 0
Views: 116
Reputation: 53
You need to allocate space to use strcpy either way with creating an array with a suffisent size or using malloc
Upvotes: 0
Reputation: 1116
When you use strcpy()
, the size of the destination string should be large enough to store the copied string. Otherwise, it may result in undefined behavior.
As you've declared the char array without specifying the size, it was initialized with the size of the string "Bye", which is smaller than the string "Hello". That's why problem occurred.
Solution:
#include<stdio.h>
#include<string.h>
int main()
{
char oldS[6] = "Hello";
char newS[6] = "Bye";
strcpy(newS, oldS);
puts(newS);
}
Upvotes: 1