Is there a way to stop the while loop below from iterating after surpassing 40? I am trying to replicate the linked list concept of iterating while NULL
pointer is not found.
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;
}
Is there are to stop the while loop below from iterating after surpassing 40
There are two ways to stop the loop: Cause the condition to become false, or jump out of the loop (break, goto, return, throw, etc.). Your loop doesn't do either.
Your condition is arr
which is false only if the pointer points to null. You never assign null to arr
, so it is never null.
I am trying to replicate the linked list concept
Linked list concepts do not generally apply to things that aren't linked lists. Arrays are not linked lists.