-1

I am new to C++

1)

#include <iostream>

using namespace std;

int main() {
    char arr[4];
    arr[0] = 'H';
    arr[1] = 'e';
    arr[2] = 'l';
    arr[3] = 'o';
    for (int i = 0; i < 4; i++) {
        cout << arr[i] << endl;
    }
    system("pause");

}

2)

#include <iostream>

using namespace std;

int main() {
    const char* arr[4];
    arr[0] = "H";
    arr[1] = "e";
    arr[2] = "l";
    arr[3] = "o";
    for (int i = 0; i < 4; i++) {
        cout << arr[i] << endl;
    }
    system("pause");
}

If I use "" for char[] array, or '' for const char*[] array, it doesn't work.

Could somebody help me figure out the difference why it happens, and explain what const char* actually means.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 2
    Possible duplicate of [Single quotes vs. double quotes in C or C++](https://stackoverflow.com/questions/3683602/single-quotes-vs-double-quotes-in-c-or-c) –  Jun 27 '18 at 17:35
  • 1
    Sidenote: this is actually undefined behavior--you need a [terminating null character](https://softwareengineering.stackexchange.com/questions/181505/what-is-a-null-terminated-string)! – scohe001 Jun 27 '18 at 17:35
  • 1
    Unlike some languages, in C and C++ there's a *huge difference* between `'a'` and `"a"`. – tadman Jun 27 '18 at 17:37
  • 3
    Worthwhile warning, but disagree with UB. Asker is not using the array as a string and doesn't need the nul terminator in their example. – user4581301 Jun 27 '18 at 18:42
  • @scohe001 Which terminating null are you referring to? – Killzone Kid Jun 27 '18 at 18:43
  • If I was new to C++, I would start by trying `std::string s = "Hello";`. C style arrays are difficult, *especially* `char` arrays. Save that for later. – Bo Persson Jun 27 '18 at 18:50
  • @KillzoneKid C-strings must be null-terminated. In the first example if he tries to pass `arr` to a function and it decays to a pointer, he's going to be in trouble. – scohe001 Jun 27 '18 at 21:21

1 Answers1

0

But if i use "" for char array or '' for const char* array it doesn't work

In the first example you create an array of 4 chars - char arr[4]; This means that every element of arr is a char. 'H' is a char, 'e' is a char, etc. So when you assign a char to array element that is a char, it works.

In your second example you create array of 4 pointers to const char - const char* arr[4]; This means every element of your array is a pointer, and it points to char which you promise not to change. "H" is a string literal, which is an array of 2 - a char 'H' and a terminating null '\0'. This array decays into a pointer to its first element, which is 'H' - a const char (same for the rest of letters). Your array is array of pointers to const char, you assign pointer to const char, so it works.

If you swap '' with "" it will not work because the types of array elements will not match with data you will be assigning.

Killzone Kid
  • 6,171
  • 3
  • 17
  • 37