【发布时间】:2017-03-05 13:43:29
【问题描述】:
我的代码:
#include <iostream>
using namespace std;
int main() {
char *test = (char*)malloc(sizeof(char)*9);
test = "testArry";
cout << &test << " | " << test << endl;
test++;
cout << &test << " | " << test << endl;
return 1;
}
结果:
004FF804 | testArry
004FF804 | estArry
我不明白我怎么可能移动了我的数组指针并且地址没有改变。
【问题讨论】:
-
&test是test本身的地址,而不是它所指向的地址。 -
好的,正如我所想,但我怎样才能得到我正在寻找的地址?
-
请注意,C++ 中从不使用 malloc。
-
@Yas - 您可能想检查答案。 :-) 此外,
test = "testArry";不会将文本移动到您malloc'ed 的内存中,它只是更改指针(并泄漏分配的内存)。您可以永远通过测试弄清楚 C 样式字符串是如何工作的,您将必须阅读它(例如strcpy)。否则使用 C++std::string并避免很多麻烦。 -
当我询问它时,没有任何答案。我正在解决一个练习,我只使用来自 c++ 的 IO 进行测试。在练习规则中,他们标记我们不得使用 string.h 和除 char(和 char*)以外的其他数据类型。
标签: c++ arrays string pointers