Reputation: 355
I may be completely missing the point here but I have the following method to print out the args in a cpp program in visual studio:
int _tmain(int argc, char* argv[])
{
char* fu = "Bar";
std::cout << "Test, " << argc << ", " << argv[0] << ", " << argv[1] << ", " << fu << endl;
printf("%s, %s, %s", argv[0], argv[1], fu);
return 0;
}
The problem I am having is it only seems to print the first character of the args and not the whole string.
From what I can tell, argv[0] dereferences the argv array to get a char*, and this is what I am passing into the cout/printf functions. They should then print all the characters up to a \0 character.
I created the test char* fu to see if the problem was with passing in a char* to the functions, but 'Bar' is successfully printed.
The only thing I can think is because the size of fu is known at compile time and the size of argv isn't something funny is going on with the way it is compiled.
I know I can print out the contents by looping through the characters but this seems to defeat the point, for example what if I want to work with the strings for comparison or something. Can someone please explain what's going on?
Upvotes: 0
Views: 3443
Reputation: 6555
The problem is, you are using probabbly Uni-Code char set. so its assumed to be 16 Bit (wide char) per char. But your parsed in chars are only 8 Bits, so your placing the lower 8 Bits in to the 16 Bit area. And you let the other 8 Bits free. So inside your application, you are treating it as not-wide char-array and you are reading it Byte per Byte, so you get the first 8 Bits and the second time, you are reading from a uninitialized block, which is probably just 0000 0000 (what would set in your case a '\0' token) but it could be anything, as you haven't placed some thing in.
The best way of solving this problem would be (As far you wasn't expected to use wide chars) just go into your MSVC project properties, and choose under General->CharacterSet "use multi-byte characterset" instead of "use unicode". Then you should just rename the main into "main" and it should work in scope of your question.
Upvotes: 1
Reputation: 52471
Either change _tmain
to main
, or change char
to TCHAR
and printf
to _tprintf
. You should be using TCHAR
-based facilities consistently, or not at all.
It's clear you are building a Unicode build, and the parameters passed to you are wchar_t*
pointers, not char*
. By treating them as if they were char*
, your program exhibits undefined behavior.
Upvotes: 2