i want to write a function that get the size of an array by using pointers , where i should make a pointer points at begin of the array and another one points at the end of the array , then i have to return the size of the array at last .
int size(double *begin,double *end), any help?
C++ help plz?
The previous answer does well to explain the idea of computing the difference in bytes between two addresses, and dividing by sizeof(double) to get the number of elements. It's good to understand that, but pointer arithmetic can simplify it greatly. This also works:
int size(double *begin, double *end) {
return end - begin + 1;
}
Assuming end points to the last element of the array. The size of what begin and end point to is built into the calculation, you get it for free.
Reply:C++ stores arrays by allocating a single continuous block of memory. So if you allocate ten doubles, you allocate a block of memory:
10 doubles * (8 bytes / double) = 80 bytes
Now the pointer gives you back the location of the first byte, so how you compute the size depends on exactly what "end" means.
There are actually several possibilities:
1.) If end is the location of the last byte, then for four doubles:
begin -%26gt; xxxxxxxx xxxxxxx xxxxxxxx xxxxxxxx %26lt;- end
The answer is ((end+1) - begin) / 8.
2.) If end is the location of the last double in the array, then for four doubles:
begin -%26gt; xxxxxxxx xxxxxxxx xxxxxxxx end-%26gt; xxxxxxxx
The answer is ((end - begin) / 8) + 1.
3.) If end is the location of the first byte after the array, then for four doubles:
begin -%26gt; xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx end -%26gt; x
This is the easiest case. The answer is (end - begin) / 8.
Imagine allocating a single double starting at location zero. Then you allocate bytes at address zero, one, two, ..., seven.
So if we allocate n objects, each of size s, then we allocate n*s bytes. If the first allocated address is f, then we allocate the following locations.
first = f + 0
last = f + n*s - 1
Hope this helps!
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment