Monday, July 27, 2009

C++ question?

iam writing a c++ code that has two pointers on the array one on the begin and other on the end and it should return the size of the array, my problem is how to point the pointer at the end while i don't know the size of the array








#include%26lt;iostream%26gt;


using namespace std;


int main()


{


int arr[]={1,2,3,4,5};


int * begin=arr;


int *end=5;


return end - begin + 1;


}

C++ question?
int temp = (int)(%26amp;arr[4]-%26amp;arr[0]);


or


int begin = (int)(%26amp;arr[0]);


int end = (int)(%26amp;arr[4]);


return (end-begin)*5/4; // note don't add the one, do the mult





// that should work, hope it helps
Reply:There's no way of just knowing where an array ends. You'd have to specify the size of the array yourself and feed the pointer same constant. You could use std::vector and it's .size() function.





Just looking at your code, it should be:


int *end = begin + 5;


or more accurately:


int *end = begin + ARRAY_SIZE;


where ARRAY_SIZE is a constant that you have specified.


No comments:

Post a Comment