this program get the size if an array , i want to fix the error
#include%26lt;iostream%26gt;
using namespace std;
int main()
{
int arr[5]={1,2,3,4,5};
int * begin,*end;
begin=arr[0];
end=arr[5];
return begin-end-1;
system("pause");
return 0;
}
C++ error!!!!?
There are a few problems here.
arr[0] = the contents of the first element of the array, not its address. You need to set begin to either arr, or %26amp;arr[0].
arr[5] indexes outside the bounds of the array. I can't tell you what its value is, but you shouldn't be referencing there. Set end to %26amp;arr[4].
The address of the beginning of the array is less than the address of second, and subsequent, elements of the array. So your statement: begin - end - 1, will be a negative value.
I guess you want to use pointers, or array addresses, to compute the size. Your code should look something like this:
#include %26lt;iostream%26gt;
using namespace std;
int size(int *begin, int *end);
int main(int argc, char *argv[]) {
int a[] = {1,2,3,4,5};
int len = sizeof(a) / sizeof(*a);
cout %26lt;%26lt; "num elements in a = " %26lt;%26lt; len %26lt;%26lt; endl;
cout %26lt;%26lt; "size(a) = " %26lt;%26lt; size(a,%26amp;a[len-1]) %26lt;%26lt; endl;
}
int size(int *begin, int *end) {
return end - begin + 1;
}
Reply:This program doesn't make any sense. What have you been trying to achieve ?
The size of the array in elements is calculated as
sizeof(arr)/sizeof(int).
If you wanted address of the first and last elements, it would be %26amp;arr[0] and %26amp;arr[4] (not 5).
system("pause") will not be executed because you terminate the program by "return" before that.
flower girl dresses
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment