这个:
const char * terry = "hello";
cout<<terry;
Run Code Online (Sandbox Code Playgroud)
打印hello而不是的内存地址'h'.为什么会这样?
考虑:
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int main()
{
vector<char> vChar;
vChar.push_back('a');
vChar.push_back('b');
vChar.push_back('c');
vChar.push_back('d');
vector<int> vInt;
vInt.push_back(1);
vInt.push_back(2);
vInt.push_back(3);
vInt.push_back(4);
cout << "For char vector Size:" << vChar.size() << " Capacity:" << vChar.capacity() << "\n";
for(int i=0; i < vChar.size(); i++)
{
cout << "Data: " << vChar[i] << " Address:" << &vChar[i] << "\n";
}
cout << "\nFor int vector Size:" << vInt.size() << " Capacity:" << vInt.capacity() << "\n";
for (int i = …Run Code Online (Sandbox Code Playgroud) 当我运行以下代码时:
int i[] = {1,2,3};
int* pointer = i;
cout << i << endl;
char c[] = {'a','b','c','\0'};
char* ptr = c;
cout << ptr << endl;
Run Code Online (Sandbox Code Playgroud)
我得到这个输出:
0x28ff1c
abc
Run Code Online (Sandbox Code Playgroud)
为什么int指针返回地址,而char指针返回数组的实际内容?
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char x[100]="hello";
int s=strlen(x);
cout<<&(x[0]);
}
Run Code Online (Sandbox Code Playgroud)
如果我编译并运行它,
输出是你好的
为什么输出不是字符'h'的地址?