C++: C-style String Acting Like An Array Of Chars?

36 Views Asked by At

Hello to anyone reading this. I am new to C++. I have some conceptual questions about C-strings. I learned that C-string acts like an array from another stack discussion, but I am confused by the following:

I know that in C++, for arrays:

int int_arr[] = {1, 2, 3, 4, 5}; 
cout << int_arr << endl;        // Address of first element of the array, prints an address
cout << *int_arr << endl;       // Content of first element of the array, prints 1
// int_arr acts like &(int_arr[0]) in assignment, comparison, etc.

I expected the same behavior for C-strings, but:

char c_str[] = "Hello";
cout << c_str << endl;          // Prints "Hello"
cout << *c_str << endl;         // Prints "H"

This contradicts the behavior of the array.
The following setup has the same behavior as a C-string:

char *c_string = "Hello";
cout << c_string << endl;      // Prints "Hello"
cout << *c_string << endl;     // Prints "H"

There are two questions here:

  • Is it correct that C-string does not act like an array, and I am supposed to remember C-string with its own behavior? If it is an array, why does it act differently in the above example of arrays, not returning the address but the whole string?
  • Is the third code section simply another way of setting up a C-string? It only works when it is a char*. (Resolved)
0

There are 0 best solutions below