简体   繁体   English

C ++:数组和内存位置

[英]C++ : Arrays and memory locations

Array of characters has always managed to intrigue me. 字符数组一直吸引着我。

Lets create an array of integer type- 让我们创建一个整数类型的数组-

int a[]={1,2,34};
cout<<a;

in this case cout<<a gives us the location of the array a 在这种情况下, cout<<a给我们数组a的位置

But- 但-

char a[]="C++";
cout<<a;

gives us C++ as the display , it is quite interesting. 给我们C++作为显示,这很有趣。

1) So why doesnt the array of characters show its memory location when used with cout? 1)那么为什么将字符数组与cout一起使用时不显示其内存位置?

2) How can I find the location of an array of characters? 2)如何找到字符数组的位置?

All help would be appreciated :) 所有帮助将不胜感激:)

- Newbie in C++ with a will to learn -具有学习意愿的C ++新手

"1) So why doesnt the array of characters show its memory location when used with cout?" “ 1)那么为什么将字符数组与cout一起使用时不显示其存储位置?”

There's a specialized overload for 有专门的超载

std::ostream& operator<<(std::ostream&, const char*);

that's why you always see the characters printed, not the address. 这就是为什么您总是看到打印的字符而不是地址的原因。

"2) How can I find the location of an array of characters?" “ 2)如何找到字符数组的位置?”

You can cast to a void* pointer if you want to see the address of the char array: 如果要查看char数组的地址,可以强制转换为void*指针:

char a[]="C++";
cout << (void*)a;

or just prefix the address operator as @WhozCraig suggested in their comment 或者只是在评论中建议@WhozCraig作为地址运算符的前缀

cout << &a;

Below are two overloads of operator<< available in standard:- 以下是标准中可用的operator <<的两个重载:

std::ostream& operator<<(std::ostream&, const char*);  // _1
std::ostream& operator<<(std::ostream&, void*);  //       _2

int arr[] = {1,2,3};
cout << arr;             // This would invoke _2

char arr[] = "Hello";
cout << arr;             // This would invoke _1

char arr[] = "Hello";
cout << (void*)arr;      // This would invoke _2
cout << &arr;

Hope I'm clear 希望我清楚

First of all rake into account that there is not operator << for integer arrays. 首先考虑到整数数组没有operator <<

When you write statements like these 当您编写这样的语句时

int a[] = { 1, 2, 34 };
cout << a;

then expression a is implicitly converted to a pointer of type const void * that to select the following overloaded operator 然后将表达式a隐式转换为const void *类型的指针,以选择以下重载运算符

basic_ostream<charT,traits>& operator<<(const void* p);

As for character arrays then the C++ Standard explicitly defines overloaded operator << for type const char * 至于字符数组,则C ++标准为const char *类型显式定义了重载operator <<

template<class traits>
basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>&,
const char*);

If you want that for character arrays would be called the operator << that is defined for type const void * then you have to explicitly cast the pointer to thjis type. 如果希望将字符数组的调用称为operator << ,它是为const void *类型定义的,则必须显式将指针转换为thjis类型。 For example 例如

char a[] = "C++";
cout << static_cast<const void *>( a );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM