Reputation: 1680
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;
}
Upvotes: 0
Views: 169
Reputation: 2684
int[4] is a C array. Instead, Use C++ std::array and its iterator:
#include <array>
#include <iostream>
int main() // Print all items
{
std::array<int, 4> arr{ 10, 20, 30, 40 };
for (auto i : arr)
std::cout << i << std::endl;
}
Or:
#include <array>
#include <iostream>
int main() // Print until the 1st 0 item
{
std::array<int, 6> arr{ 10, 20, 30, 40, 0, 0 };
for (auto i : arr) {
if (i == 0)
break;
std::cout << i << std::endl;
}
}
Upvotes: 0
Reputation:
Use a reserved value such as zero and append it to the end of the array, just like with an old C string. This is called a sentinel element.
int* arr = new int[4]{ 10,20,30,40,0 };
while (*arr) {
...
Upvotes: 1
Reputation: 238421
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.
Upvotes: 0
Reputation: 2588
Because arr
is placed in a contiguous memory, you will never get a NULL value of memory address AFTER arr
.
You may try following code on online compiler.
#include <iostream>
int main()
{
int* arr = new int[4]{ 10,20,30,40 };
for(int i=0; i<4; ++i){
std::cout << *(arr++) << std::endl;
std::cout << arr << std::endl;
}
std::cout << "NULL is " << (int*)NULL; // NULL mostly stands for 0.
return 0;
}
Output might be something like this:
10
0x182de74
20
0x182de78
30
0x182de7c
40
0x182de80
NULL is 0
Why does linkedlist works? Because linkedlist stores data in non-contiguous memory and next()
would give you NULL
as a sign of the end of a list.
Also you might need a fundamental book of C++.
Here's the booklist.
Upvotes: 1