Hello ppl, was wondering if you can help with me with some pointer code.
Code:
void Menu()
{
char* phone;
char* name;
GetPhone(&phone);
GetName(&name);
// use the following printf function to test my code.
// check bottom of msg for output and what my problem.
printf("%d - %s - %d - %s", &name, name, &phone, phone);
}
void GetName(char** nameRef)
{
int ch;
char buffer[100]; /* buffer used to get input from the user.
if the user enters in 105 characters for name
the buffer will reset to 5
*/
printf("(Name must be between 3-20 characters in length)\nEnter a name to be added to the list: ");
fgets(buffer, sizeof(buffer), stdin); // gets input from stdin and puts in buffer
while ((ch = getchar()) != '\n' && ch != EOF);
*nameRef = buffer;
//printf("%d - %s", &nameRef, *nameRef);
if((strlen(*nameRef)-1 < 3) || (strlen(*nameRef)-1 > 20))
{
printf("Name has to be between 3 and 20 characters long.\nPress [Enter] key to be prompted again.");
GetName(nameRef);
}
}
void GetPhone(char** phoneRef)
{
int ch;
char buffer[50];
printf("Enter the phone number to be added to the list: ");
fgets(buffer, sizeof(buffer), stdin);
//while((ch = getchar()) != '\n' && ch != EOF);
*phoneRef = buffer;
printf("%d - %s", &phoneRef, *phoneRef);
if(strlen(*phoneRef)-1 != 9)
{
printf("The phone number you entered has too many digits.\nMust be in either xxxx xxxx or xxxx-xxxx formats.\nReplace x with numbers.");
GetPhone(phoneRef);
}
if(!((buffer[4] == ' ') || (buffer[4] == '-')))
{
printf("Must be in xxxx xxxx or xxxx-xxxx formats. Replace x with numbers.");
GetPhone(phoneRef);
}
if(validate_phone(*phoneRef) != 0)
{
printf("The phone number you have entered contains non-numeric data. Try again.");
GetPhone(phoneRef);
}
}
int validate_phone(char* phoneRef)
{
unsigned x;
for (x = 0; x < strlen(phoneRef); x++)
{
if(phoneRef[x] == phoneRef[4])
break;
if(!isdigit(phoneRef[x])) return 1;
}
return 0;
}
output of test printf statement: & it does go to the new line like that
601364 - paul
- 601368 - 5074-0658
problem is when i put a printf statement in the GetPhone and GetName functions and notice that the reference address of the name pointer is the same as the one for phone reference. problem is whenever i try and get the string entered in GetName i get weird ASCII characters.
What i'm try to do is create a simple phone book using a link list structure to hold the data, as a exercise to try and understand pointers.
Thx in advance
catalyst