我对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元素的内存地址?如何获取个别条目的地址?谢谢!
在最后一行中,表达式&(input[0])确实会导致char数组的第一个char的地址,这是char数组的地址input.所以你的代码很有用.
但输出操作符<<有一个有用的重载,char *并将char数组的竞争作为C字符串打印(打印所有字符,直到找到零字符).
要打印地址,请执行以下操作:
void *p = input;
std::cout << "p=" << p << "\n";
Run Code Online (Sandbox Code Playgroud)