Re: Can't find last element in list
desktop wrote:
How do I find the last element in the list numsx defined below?
int* myfind(int* arr_start, int* arr_end, int& s) {
Why is 's' passed by
int not_found = 666;
int* result = ¬_found;
while (arr_start != arr_end){
if (*(arr_start) == s)
{
result = arr_start;
}
arr_start++;
}
return result;
Clutter, clutter... Given the interface (forget the 666) you
should implement this as
while (arr_start != arr_end) {
if (*arr_start == s)
break;
++arr_start;
}
return arr_start;
}
int main() {
int numsx[] = { 1, 2, 3, 4, 5, 7, 8, 9};
int* resultx;
int endx = (sizeof(numsx)/4)-1;
Two mistakes. First, don't use 4, use 'sizeof(int)'. Second,
you're much better off if you don't subtract 1. Use the range
where the upper value is not includede (this is called "an open
range"). IOW
int endx = sizeof(numsx) / sizeof(numsx[0]);
int sx = 9;
resultx = ::myfind( numsx, numsx + endx,sx);
Since 'resultx' is a pointer, it could be equal to 'numsx + endx',
which will mean "not found".
std::cout << *resultx << std::endl;
return 0;
}
I have thought about:
while (arr_start != arr_end+1){
...
...
instead, but since "arr_end+1" is unknow territory I guess its bad
style.
No, it's actually better.
Is there someway to make sure that the last element in a list is read
and only terminate afterwards?
See above.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask