On Apr 26, 10:52 am, desktop <f...@sss.comwrote:
I have a function that takes two pointers to an array. The first point
to the first element while the other points to the last element.
int nums[] = { 1, 2, 3, 4, 5, 7, 8, 9};
int* result;
int end = (sizeof(nums)/4)-1;
An integer on my system is not 4 bytes.
int s = 7;
result = ::myfind(nums, nums + end, s);
the implementation goes like:
int* myfind(int* arr_start, int* arr_end, int& s) {
int arr_size = (arr_end - arr_start)+1;
int* result = arr_end;
for (int i = 0; i < arr_size; i++) {
if (*(arr_start+i) == s)
{
result = arr_start+i;
}
}
return result;
}
I have been told that elements in an array does not necessary lie after
each other in memory. So if I wanted a char array or string array
instead I guess the above function would not work?
In that case how do I make sure that I access the right elements in the
right order in an array and that I can calculate its size with:
int arr_size = (arr_end - arr_start)+1;
What padding a particular compiler might give to some type is not your
concern.
sizeof() will return the size including the padding, if any.
Both arrays and std::vector hold elements in contiguous memory space.
The problem is you can't assume that an integer has 4 bytes, let the
compiler/platform decide that.
On mine, its 8 bytes (but i don't care).
The term 'end' does not depict the last element, it points to one past
the last element.
So once you've reached the end, you are no longer in the container.
back() usually returns the last element.
You are aware that your array has 8 elements, right? Its got no 6.
Replace all T's with int if templates disturb you.
#include <iostream>
template< typename T >
T* find_ptr(T* const pbegin, T* const pend, const T& t)
{
size_t size = pend - pbegin;
std::cout << "size = " << size;
std::cout << std::endl;
for(T* p = pbegin; p != pend; ++p)
{
if(t == *p)
return p;
}
return pend;
}
int main()
{
int nums[] = { 1, 2, 3, 4, 5, 7, 8, 9 };
// p_end is one past the end of container
int* const p_end = &nums[ sizeof(nums)/sizeof(int) ];
int* p_result = find_ptr(&nums[0], p_end, 7);
// if p_end wasn't returned, something was found
if( p_end != p_result )
{
std::cout << "found at: " << p_result;
std::cout << "\tvalue: " << *p_result;
std::cout << std::endl;
} else {
std::cout << "p_end reached, element not found.\n";
}
}
/*
size = 8
found at: 0x7fff7ef0e554 value: 7
*/
/* another way... pass the whole array by reference
template< typename T, const size_t Size >
T* find_ref(T (& array)[ Size ], const T& t)
{
size_t size = sizeof(array)/sizeof(T);
std::cout << "size = " << size;
std::cout << std::endl;
for(size_t i = 0; i < size; ++i)
{
if(t == array[i])
return &array[i];
}
// one past the last element
return &array[Size];
}
*/