why does printing address of c string returns the entire string?


why does printing address of c string returns the entire string?

let's say I have a char cString[] {"HELLO WORLD"}

1. why does printing out the &cString[0] returns the entire string or &cString[1] will return a substring of cString and it does not return a hexadecimal address like other primitive array?

for example:

if I print &intArray[0] It will print a hexadecimal address out unlike the &cString[0] which will print out the entire string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

          #include <iostream>
 
using namespace std;
 
int main()
{
      char cString[] {"HELLO WORLD"};
      //can also be written as
      const char* cPtr {"HELLO WORLD"};
 
      int intArray[] {2, 4, 5, 6, 7, 8};
 
      cout << &cString[1] << endl;
      cout << *(&cString[1]) << endl;
 
      cout << "printing cString:  " << cString << endl;
      cout << "printing &cString[0]:  " << &cString[0] << endl;
      cout << "printing &cString:  " << &cString << endl;
 
      cout << "\nprinting intArray:  " << intArray << endl;
      cout << "printing &intArray[0]: " << &intArray[0] << endl;
 
}
Last edited on
It's as by design. cout treats a type of char * as a pointer to a c-style null terminated string and displays that string. If you want to display the address of a char* type then first cast to void *

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
include <iostream>

using namespace std;

int main() {
	char cString[] { "HELLO WORLD" };
	//can also be written as
	const char* cPtr { "HELLO WORLD" };

	int intArray[] { 2, 4, 5, 6, 7, 8 };

	cout << &cString[1] << endl;
	cout << *(&cString[1]) << endl;

	cout << "printing cString: " << cString << endl;
	cout << "printing &cString[0]: " << static_cast<void *> (&cString[0]) << endl;
	cout << "printing &cString: " << static_cast<void *> (&cString) << endl;

	cout << "\nprinting intArray: " << intArray << endl;
	cout << "printing &intArray[0]: " << &intArray[0] << endl;
}


Worldtreeboy,
Please learn to use code tags, they make reading and commenting on source code MUCH easier.

How to use code tags: http://www.cplusplus.com/articles/jEywvCM9/

There are other tags available.

How to use tags: http://www.cplusplus.com/articles/z13hAqkS/

HINT: you can edit your post and add code tags.

Some formatting & indentation would not hurt either

seeplus tagged your code so you see the difference.
Thanks. I edited my code.
Topic archived. No new replies allowed.