【发布时间】:2020-07-29 12:33:58
【问题描述】:
有没有办法阻止下面的 while 循环在超过 40 之后进行迭代?我正在尝试复制链表的迭代概念,而 NULL 找不到指针。
int main() {
int* arr = new int[4]{ 10,20,30,40 };
//for(int i=0; i<4; ++i) -- works fine
while (arr) {
cout << *(arr++) << endl;
}
delete[] arr; // Free allocated memory
return 0;
}
【问题讨论】:
-
指针在到达数组末尾时不会变为 NULL。 C++ 不能以这种方式工作。
-
简答:否。
-
(arr+4) 不为空。你可以试试
std::cout<< (arr++)看看你得到了什么。 -
链表概念适用于链表。动态数组在现代 C++ 中是一种难闻的气味。你想要一个
std::vector。 -
int count = 4; while(count--) { ... }
标签: c++ arrays pointers pointer-arithmetic