字符数组如何存储在内存中?

How is char array stored in memory?

本文关键字:内存 存储 数组 何存储 字符      更新时间:2023-10-16

我对字符数组的内存地址感到困惑。以下是演示代码:

char input[100] = "12230 201 50";
const char *s = input;
//what is the difference between s and input?
cout<<"s = "<<s<<endl;                    //output:12230 201 50
cout<<"*s = "<<*s<<endl;                  //output: 1
//here I intended to obtain the address for the first element
cout<<"&input[0] = "<<&(input[0])<<endl;  //output:12230 201 50

字符数组本身是一个指针吗?为什么&运算符不给出char元素的内存地址?如何获取单个条目的地址?谢谢!

在最后一行中,表达式确实&(input[0])产生 char 数组第一个 char 的地址,即 char 数组input的地址。所以你的代码有点工作。

但是输出运算符<<有一个有用的重载char *并将 char 数组的竞争打印为 C 字符串(打印所有字符,直到找到零字符)。

要打印地址,请执行以下操作:

void *p = input;
std::cout << "p=" << p << "n";

尽管在大多数情况下,数组可以被认为是指向数组中第一个元素的指针,但它们并不等同于指针。从技术上讲 - 数组衰减到指针。

&(input[0])返回一个char*,该具有打印实际字符串的重载。要打印地址,您可以使用static_cast<void*>(&input[0]).