Sunday, August 2, 2009

C++ program help?

i want to write a function that get the size and the max element in an array using pointers , plz help me !!

C++ program help?
This is a pretty good exercise to learn a few things about pointers. The somewhat tricky part of this is that your function doesn't know how big the array is; actually, you want it to tell you how big it is. Kind of silly, since the caller is likely to know the size already, but hey, it's just an exercise. One approach, as I've done below, is to have a well known value that marks the end of the array. Slightly more clever would be to have the caller pass in the end marker to the function, rather than having it be a global.





Note also that there's nothing particularly C++ - ish about this code. Except for the cout statement, it's C.





If this is for an assignment, don't just turn in my code as if it were your own. Study my code, learn something, then code it for yourself. Since this is such fundamental stuff, your code may look a lot like mine, which is ok.





#include %26lt;iostream%26gt;


#include %26lt;climits%26gt;





using namespace std;





void sizeMax(int *, unsigned *, int *);





static const int END = 0xDEAD;





int data[] = { 10, 3, 42, 1, -1, 11, 0, END };





int main(int argc, char *argv[]) {


unsigned size;


int max;





sizeMax(data,%26amp;size,%26amp;max);


cout %26lt;%26lt; "size = " %26lt;%26lt; size %26lt;%26lt; ", max = " %26lt;%26lt; max %26lt;%26lt; endl;





return 0;


}





void sizeMax(int *a, unsigned *size, int *max) {


int *p;


*size = 0;


*max = INT_MIN;





for (p = a; *p != END; p++, (*size)++) {


if (*p %26gt; *max) *max = *p;


}


}
Reply:#include %26lt;stdio.h%26gt;


#include %26lt;limits.h%26gt;





// macro to determine size of an array


#define SizeofArray(a) ((sizeof(a) %26gt; 0) ? (sizeof(a)/sizeof(*a)) : 0)





void GetMaxAndSize(int * pArray, int %26amp; nSize, int nMax)


{


nSize = SizeofArray(pArray);


nMax = INT_MIN;


int nIndex;


for(nIndex = 0; nIndex %26lt; nSize; nIndex++)


{


if(nMax %26lt; *pArray) nMax = *pArray;


pArray += 1;


}


}











// example


int Numbers[]={1,2,3,4,5,6,7,8,9,10};





int main(int argc, char* argv[])


{


int nSize;


int nMax;


GetMaxAndSize(Numbers, nSize, nMax);


return 0;


}


No comments:

Post a Comment