作为 C++ 的初学者,我很难理解指针和数组。我编写了以下程序:
int main (void){
int p[3]={0};
int * iptr = new int [4];
iptr++;
*iptr=2;
iptr++;
*iptr=3;
for (int i=0;i<4;i++){
cout << "iptr: " << *iptr << endl;
iptr++;
}
return 0;
}
但是我没有得到预期的结果。我希望元素 [1] 和 [2] 分别具有值 2 和 3。但是我得到的结果是:
iptr: 3
iptr: -842150451
iptr: -33686019
iptr: 0
谁能告诉我我的理解哪里出了问题?
谢谢 丹
最佳答案
As a beginner to c++ I'm struggling to understand pointers and array
任何人都可以给你的最好建议:不要。指针和数组不值得付出努力。使用像 std::vector
或 std::array
这样的 C++ 工具,您的生活将会变得无比轻松。如果需要,请在掌握了其余语言后回来学习它们。
关于c++ - 数组和指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10127309/