Weird characters in char array

Hi, I'm new to c++. I was playing around with char arrays but i somehow end up with strange characters in my final char array when i try to join 2 together(example ╝■(alfred nathan). When i change the array size from 20 to 10, I get no problems. Some help here please! Thanks in advance for any help that i can get :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <cstring>


using namespace std;

int main()
{
    char first[20];
    char last[20];
    char name[40];

    cout << "Enter your first name" << endl;
    cin >> first;
    cout << "Enter your last name" << endl;
    cin >> last;

    strcat(name,first);
    strcat(name," ");
    strcat(name,last);

    cout << name;

    return 0;
}






strcat() will add the new string to the existing string.
So the question is, what is the existing contents of name?
ohh, so am i right to say that even if i dont initialize name at the start, it will still contain a value?

so i must initialize name with a null value?
Last edited on
Yes. It might happen to contain zero values, which will be interpreted as an empty string, but really it could contain anything at all, just whatever happens to be at that memory location from some previous use. The answer, as I think you figured out, is to give it an initial value , perhaps like this,
 
     char name[40]  = "";


(if you use c++ std::string, that is automatically initialised as an empty string).
Last edited on
Ahh i see. Okay thank you very much for clearing that up for me :)
Topic archived. No new replies allowed.