Parameter Passing Help
Author |
Message |
jin
|
Posted: Fri Mar 02, 2007 1:01 am Post subject: Parameter Passing Help |
|
|
Hey i have a function that has parameters of an int and a pointer to an object. i am passing in an int and an address of an object. the function finds the object with the int value. i would like to change the address of the object being passed in to the to the one in the function. how would i go about doing this.
PS: cannot change parameters to references and cannot change return type.
if u dont understand that
in main
code: | Database.retrieve(x, &tempRecord) |
the function
code: | retrieve(unsigned int studentNum, studentRecord* searchRecord)
{
for (int index = 0; index < _next_index; index++)
{
if (_arrayDB[index]->getStudentNumber() == studentNum)
{
searchRecord = _arrayDB[index];
}
}
} |
i want tempRecord in main to have address of _arrayDB[index]
appreciate any help |
|
|
|
|
|
Sponsor Sponsor
|
|
|
abcdefghijklmnopqrstuvwxy
|
Posted: Sun Mar 04, 2007 7:23 pm Post subject: RE:Parameter Passing Help |
|
|
code: |
retrieve(unsigned int studentNum, studentRecord* searchRecord //a pointer named searchRecord points to the address of tempRecord)
{
for (int index = 0; index < _next_index // where is this declared?; index++)
{
if (_arrayDB[index]->getStudentNumber() == studentNum)
{
searchRecord = _arrayDB[index]; //now the pointer searchRecord points to the studentRecord* located at index. We haven't changed tempRecord.
break;
}
}
}
|
But what is tempRecord exactly? It is an object you created on the stack. Not a pointer. When you pass it's address to this function you can manipulate that object, but you can't turn that object into a pointer by supplying its address.
In order for tempRecord to have an address which can be changed you need to declare it as a pointer, not an object.
code: |
studentRecord* tempRecord = new studentRecord;
//then pass it to the function like so:
Database.retrieve(num, tempRecord);
|
But you mentioned you cannot change any parameters. Well, without changing any parameters you CANNOT change the address of tempRecord to anything, because it is not a poitner. But you could make the value of tempRecord equal the value of _arrayDB[index]. How? First be sure to overload the = operator in your class declaration. Then,
code: |
*searchRecord = *_arrayDB[index];
|
If you don't know about overloading the = operator than google it or find the answer in these forums. wtd covered it a few times I think in the tutorial section. |
|
|
|
|
|
|
|