I'm trying to concatenate another string onto arg[0].
#include <stdio.h>
#include <string.h>
int main() {
char* arg[] = {
"Hello",
NULL,
NULL,
NULL
};
strcat(arg[0], " World");
}
This returns abort trap.
What am I doing wrong?
You are trying to rewrite a string literal with:
char* arg[] = { "Hello", ..... }; // "Hello" is a string literal, pointed to by "arg[0]".
strcat(arg[0], " World"); // Attempt to rewrite/modify a string literal.
which isn´t possible.
String literals are only available to read, but not to write. That´s what make them "literal".
If you wonder about why:
char* arg[] = { "Hello", ..... };
implies "Hello"
as a string literal, You should read the answers to that question:
What is the difference between char s[] and char *s?
By the way, it would be even not possible (or at least get a segmentation fault at run-time) if you would do something like that:
#include <stdio.h>
#include <string.h>
int main() {
char a[] = "Hello"; // 6 for holding "Hello" (5) + "\0" (1).
strcat(a, " World");
}
because the array a
needs to have 12 characters for concatenating both strings and using strcat(a, " World");
- "Hello"
(5 characters) + " World"
(6 characters) + \\0
(1 character) but it only has 6 characters for holding "Hello"
+ \\0
. There is no memory space added to the array automagically when using strcat()
.
If you execute the program with these statements, you are writing beyond the bounds of the array which is Undefined Behavior and this will get you probably prompt a Segmentation Fault error.
One of the shortcomings of C strings is that you need to know how big they will be ahead of time.
#include <stdio.h>
#include <string.h>
int main() {
char arg[1024] = "Hello";
strcat(arg, " World");
printf("%s\n", arg);
}
In this case, the size of the concatenated string must be less than 1024 characters. This is why it is safer to use something like C++, where you have std::string
to prevent these types of issues.
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.