#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *hi = "bye";
char *bye = "abc";
strcat(hi, bye);
printf("%s\n", hi);
}
How would I concatenate these variables? Everything I'm trying crashes it
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *hi = "bye";
char *bye = "abc";
strcat(hi, bye);
printf("%s\n", hi);
}
How would I concatenate these variables? Everything I'm trying crashes it
You can't. String literals are non-modifiable.
You can if you make a copy out of it which is modifiable. Here the char
array is initialized with the content of the string literal.
char hi[10]="bye";
...
This will work.
In your case by using strcat
on string literal you are invoking undefined behavior.
From 6.4.5p7
It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
Also from J2: Undefined behavior listings from standard
The program attempts to modify a string literal
Note that even if string literal was modifiable then also it would not be a defined behavior to concatenate strings. While concatenating strings make sure the string on which you are concatenating has enough space - otherwise it would try to write beyond the char array which itself will invoke undefined behavior. One thing you can see for yourself on the light of what I said in this paragraph (char array initialized with string literal's value),
char hi[]="bye";
Then using strcat
would lead to undefined behavior.
String literal is immutable. Any attempt to modify it invokes undefined behavior.
You'll be able to modify it if you store the target string in an array:
int main()
{
char hi[10] = "bye";
char *bye = "abc";
strcat(hi, bye);
printf("%s\n", hi);
}
Quoting C standard draft N1570, section 6.4.5/7:
It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
See more at Why do I get a segmentation fault when writing to a string initialized with "char *s" but not "char s[]"?