一个基本的 C++ 字符串/指针问题。问题包含在最后的评论中 - 即为什么最后一行中的 [0] 不产生“john”?
#include <iostream>
using namespace std;
void funk(char* a[]);
int main() {
char* z[5];
z[0] = "john";
z[1] = "susan";
z[2] = "holly";
z[3] = "simon";
z[4] = "lucinda";
funk(z);
cin.get();
return 0;
}
void funk(char* a[]) {
cout << a[0] << endl; // prints 'john'.
cout << *a << endl; // prints 'john'.
a++;
cout << *a << endl; // prints 'susan'.
a++;
cout << *a << endl; // prints 'holly'.
cout << a[0] << endl; // prints 'holly' again. But why?! Why doesn't it print 'john'?
}
最佳答案
两个之后
a++;
a
指向向前的两个元素。现在新的 a[0]
实际上与之前的 a[2]
相同,因此打印 holly
。
关于C++指针数组似乎不符合逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25300448/