Printing character arrays

As the character array "char* argsv[]" (the second argument for the main() method) contains the executable path in element[0], you can print the array of characters making up the patch using:

 
cout << argsv[0];


This displays on the console perfectly fine, however if I make my own array of characters and try to display this in the console, I have an interesting result.

The outcome is the character array displayed correctly, however there are some random characters proceeding. This is the snippet:

1
2
3
4
5
6
char year[4];
year[0] = '2';
year[1] = '0';
year[2] = '1';
year[3] = '5';
std::cout << year << std::endl;


Can anyone shed some light as to why this happens?
Last edited on
Character array (or character pointer) output expects a null-terminated character sequence. That means that there should be a null character '\0' after last symbol. Also that means that your array should be one large than amount of characters in it.
1
2
3
char year[5] = {'2', '0', '1', '5', '\0'};
//or
char year[] = "2015"; //Null character exist in string literals by definition 
Thank you very much. Reading more into this now!
Topic archived. No new replies allowed.