0
int* arr = new int[30](); //30 is random serving the example's purposes

while(<insert check here that uses the arr pointer>){

   cout<<*arr<<endl;

   arr++;
}

This is me experimenting on tricks using pointers and I have been working on this for some time today. I have used many different checks in the while clause without ever getting it right (mostly ending up with infinite loops or seg faults). So my question can this be done or the standard for-loop method is the only way?

1
  • 2
    Note that by incrementing arr, the only pointer you have to that memory allocation, you've lost the ability to delete[] it without an extreme amount of effort. Make a copy before you start incrementing it. Commented Feb 15, 2017 at 1:24

1 Answer 1

1

Well, there are many ways to do this.

add

int *end = arr + 30;
while (arr < end)

Of course, by incrementing "arr", you are losing the pointer to the array - but you knew that already :-)

Sign up to request clarification or add additional context in comments.

8 Comments

I thought when I increment arr I just move on to the next element of the array...why am I losing the pointer? And second your answer is nice but I try to do the check without using the size of the array just by checking the pointer alone
C++ doesn't track the size of the array - so you need to do this manually.
So there isn't something that indicates that the pointer reached the end of the array? Something similar like the null termination in strings.
Use std::vector<> instead of a raw array - now it will track it for you.
It is undefined. Accessing arr[30] may give you a segfault (terminating the program), or may return the value 0, or some other random value. In fact, given "a=new int[10]; b=new int[10]", it is possible that "a[15]" references part of b - of course you cannot depend on this in any way. It may be instructive to add "printf("arr is %p\n", arr);" inside your loop, and just before the start of the loop.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.