(Tommy Lang) wrote in message news:<. com>...
Your code seems to be okay other than the name comparision. You should
use strcmp instead of using a double equals operator. But I have a few
suggestions to improve your code: Follows
> Hi!
>
> I am trying to write a function that goes through an array of
> objects(class Student) and checks if
> object name(student name)matches search string(char *). I want the
> function to return a pointer to the object, if a match is found.
>
> This is my code so far...(am I even close?
)
>
> //I want to return a ponter of type student
> Student *List::find(char *chName) //chName is the name i want to look
When you are using C++, it's always better to use std::string than
using char* . std::string is a container of char* and provides you
lots of facilities and will free you from dealing with the pointer
stuff.
> for
> {
> //Check whole array
> for(int i=0;i<100;i++)
Where did you get the upper limit of the interation; 100, from? Are
you limiting your list to contain just 100 students? I guess this
problem is because of the usage of arrays (I guess the below MyArray
stuff). Here goes the second suggestion: Always prefer using a
std::vector or anyother container rather than using arrays. This is a
strong suggestion. If you would have used a vector like
std::vector<Student*> m_vecStudents, you can get the size of the
vector using vector.size(). This would help you in not letting an
upper limit to your List size.
> {
> Student *temp;//Create a temp pointer
> temp = MyArray[i]; //Add current array value(object) to temp
>
> char *name;//Create a char pointer
> name = temp->get_name();//Get object name (public method of
> Student)
>
> if(name == chName)//Compare names
Use strcmp for the comparision. If you use std::string s, then you can
use the double equals operator for the comparision.
> {
> return temp; //return pointer to object if found
> }
> }
> return NULL; //return NULL if it was not found
> }
>
>
> A correct call would be ...???
> Student *s = find(NameToFind);
> if(s!=NULL)
> //do something....
>
>
> Thx,
> Tommy
HTH,
Kalyan