Hi, I’ve got a code problem that I suspect has got something to do with working with pointers. I started with a function with the following prototype...
char* getPhone(byte num);
it’s purpose is very simple, I pass it a number and it returns a pointer to phone number from a list. If I pass a ‘1’ I get the first number from the list, a ‘2’ returns the 2nd number etc etc. I’ve used this function for ages and it seems to work fine.
I need a variation of this function that will return true or false depending on whether or not the phone number actually exists as well as returning a pointer to the number. This is needed for those occasions when the code asks for 3rd number in a list that only contains (for example) 2 numbers. This is what I came up with.....
bool ConfigMan::getPhone (byte num, char * crewPhone)
{
crewPhone= getPhone (num);
// Check that the length of the phone number is within acceptable limits
if ((strlen(crewPhone) <= 7) || (strlen(crewPhone) > 15) )
{
// Phone number is too short (or long) to be plausable
return false;
}
else
{
return true;
}
}
This code also appears to work when I test it against the original version using the following code snippet.....
for (byte x =0;x<=3;x++)
{
crewNum=confData. getPhone (x);
Serial.print("crew # <");Serial.print(x,DEC);Serial.print(">. Phone number is <");Serial.print(crewNum);Serial.println(">");
}
for (byte x =0;x<=3;x++)
{
if (confData. getPhone (x, crewNum) == true)
{
// crew number is available
Serial.print("crew # <");Serial.print(x,DEC);Serial.print(">. Phone number is <");Serial.print(crewNum);Serial.println(">");
}
else
{
// crew number not valid
Serial.print("crew # <");Serial.print(x,DEC);Serial.println(">. not valid / unavialable ");
}
}
I get the following results....
crew # <0>. Phone number is <+445554076240 >
crew # <1>. Phone number is <>
crew # <2>. Phone number is <>
crew # <3>. Phone number is <>
crew # <0>. Phone number is <+445554076240 >
crew # <1>. not valid / unavialable
crew # <2>. not valid / unavialable
crew # <3>. not valid / unavialable
So far so good, everything is behaving as I hoped. The catch is that when the getPhone() function is incorporated in a object that is then passed as an parameter to another function it stops working i.e. the pointer seems to point to some random memory location rather than the selected phone number.
In summary...
myObject.getPhone() seems to work.
myObject->getPhone() never works.
Sadly my knowledge of pointers is at best flakey. I’ve tried my normal technique of randomly inserting ‘*’s and ‘&’s with no success, I’m sure the solution is quite trivial, please can someone enlighten me?
Cheers