how to set a char?

The following is wrong,but why is it wrong? what's the correct way to set a char?
1
2
char a;
a = "Hello World";
the correct code is

1
2
3
4
string a;

a="Hello World";


char *a;
a = "Hello world";
dont get it...
*a means a pointer that points to a...why is that?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    char a;
    a = 'H';
    
    // or 
    const char *b = "Hello World";
    
    // or 
    char c[] = "Hello World";
    
    // or
    char *d = new char[12]; // remember to add 1 for null terminator
    strcpy(d, "Hello World");
    
    
    cout << a << endl;
    cout << b << endl;
    cout << c << endl;
    cout << d << endl;


However, as odai points out, in C++ std::string is preferred.

if you want a single character you do

1
2
char a;
a = 'H';


if you require an array of characters you need the *

1
2
char *a;
a = "Hello World";


or
1
2
std::string a;
a="Hello World";
*a means a pointer that points to a...why is that?

A c-style string is a sequence (or array) of characters which is terminated by a zero-byte (null terminator).

A pointer such as char * a; points to the first character in the string.
closed account (Dy7SLyTq)
what a char * actually is:
{'H', 'e', 'l', 'l' /*etc, etc*/} however in c(++) we are allowed to treat it kind of like a string type upon initialization.
char means single, value.
such as
a
b
c

"Hello World" is a string of charcters.
You can use it with a string, or a char array
string mystring;
or
char mystring[11];

In the last example mystring[1] is equal to the single char "H".
I know now. thanks for your explaination.
Topic archived. No new replies allowed.