Newbie here. I'm trying to concat the args of a C++ program into a single char array. For some reason, strcat
is selectively ignoring argv[2]
in the for-loop:
#include <cstring>
int main(int argc, char *argv[]) {
char *argstr = argv[1];
for(int i=2; i < argc; i++) {
argstr = std::strcat(argstr, " ");
argstr = std::strcat(argstr, argv[i]);
}
std::cout << argstr << std::endl;
return 0;
}
The file is named qtimer
. So, the expected output of running:
qtimer asdf 1 2 3
would be:
asdf 1 2 3
but instead it's outputting:
asdf 2 3
(with two spaces after asdf
)
Could anyone explain why this is? Also, is there a better way of doing this?
You are appending to the string stored in argv[1]
, but you don't know that there is space there. You are overwriting memory that does not belong to you.
This is undefined behavior, and anything could happen.
Most likely, the memory you are overwriting is the memory where the other arguments are stored, so that by the time you are accessing them, they are already corrupted.
You should use std::string
for string operations in C++, it is much better and safer.