I was learning string.h
header file and wrote a simple program to concatenate two strings.
The simple C program
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "sandeep";
char str2[] = "sahani";
strcat(str1, str2);
printf("%s %s", str1, str2);
return 0;
}
Got an error which says:
"/Users/sandeepsahani/Desktop/Sandeep Sahani/Basic Programming/ C programming/Basic Programs/DS/"stringConcat zsh: illegal hardware instruction
What's wrong with my code?
couple of problems here:
int main()
{
char str1[] = "sandeep";
char str2[] = "sahani";
char str3[100] = {0};
strcat(str3, str1);
strcat(str3, str2);
printf("%s %s %s", str1, str2,str3);
return 0;
}
If you don't specify the size of an array, the size is just enough to hold the values it's being initialized with. So str1
only has 8 characters (7 characters plus the null terminator). That's not enough room to add sandeep
to it.
If you want to concatenate to it, you need it to have room for the additional string. Since str2
is 6 characters, str1
needs at least 14 characters. So change it to:
char str1[14] = "sandeep";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.