char数组如何存储在内存中?

jin*_*imo 3 c++

我对char数组的内存地址感到困惑.这是演示代码:

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
Run Code Online (Sandbox Code Playgroud)

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

Joh*_*ann 5

在最后一行中,表达式&(input[0])确实会导致char数组的第一个char的地址,这是char数组的地址input.所以你的代码很有用.

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

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

void *p = input;
std::cout << "p=" << p << "\n";
Run Code Online (Sandbox Code Playgroud)

  • @jingweimo"\n"只是一种在输出流中输出换行符的方法.`std :: endl`输出换行符,但也刷新输出缓冲区.通常不需要手动刷新缓冲区,所以很多人更喜欢"\n"或"\n"(在某些情况下可能更快). (2认同)