Questions about c++ cout

Asked 1 years ago, Updated 1 years ago, 67 views

Hello, everyone I am a student studying c++.

I am inquiring because there is something strange while studying c++.

==================

char c = 'a';

char *d = &c;

cout << d << endl;

printf("%p\n",d);

===================

I understand that the address value of mode c will be printed in two cases if it is done as above.

However, in the case of cout, it is not an address value, but a strange value is continuously printed, so I want to know why.

c++ c printf cout char*

2022-09-22 18:48

1 Answers

Printf sets the format to %p, i.e. explicitly output the address.

cout is outputting variable results, not addresses.

The reason why the strange value is output is that char* is a little unique, unlike other types. char* is also the definition of a string, with the end of the string definition being null characters. That is, it recognizes that before the null character is a single string, so it is output together until a strange value, that is, null appears.

Just memorize this part. Char* is different from int*. Char* must represent a string, and the string ends with a null character. The variable name also represents a string value, not an address.

In other words, if you do cout <<d, you print it out until you get a null character, even though you substituted only one character. If you want to output only one character, you must express it explicitly, such as d[0].


2022-09-22 18:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.