Reputation: 107
I am new to C language and trying to create a simple program to return name and age. I created a working function for returning the name but this does not work for returning the int.
The code I have now is:
int * GetAge(){
int Age;
printf("What is your age: ");
scanf(" %d", &Age);
int * returnedage = Age;
return returnedage;
}
This is GetName():
char * GetName(){
char Name[31];
printf("What is your name: ");
scanf("%s", Name);
char * returnedname = Name;
return returnedname;
}
The warning is on this line:
int * returnedage = Age;
It says:
incompatible integer to pointer conversion
initializing 'int *' with an expression of type 'int'; take
the address with &
I have tried:
int * returnedage * Age;
int * returnedage & Age;
//for strcpy I set the function as a char
char * returnedage;
strcpy(Age, returnedage);
None of these work.
I want to just get the name and age then in main I am printing the name and age with:
printf("Your name is %s and your age is %d", GetName(), *GetAge());
This does not have any errors.
So my expected Output is:
What is your name: Ethan
What is your age: 13
Your name is Ethan and your age is 13
What I actually get is:
What is your name: ethan
What is your age: 13
exit status -1
Please tell me if there is a basic solution for this.
Upvotes: 0
Views: 19338
Reputation: 703
Change your code to this:
int GetAge()
{
int Age;
printf("What is your age: ");
scanf(" %d", &Age);
return Age;
}
On main (Remove the * on the GetAge()):
printf("Your name is %s and your age is %d", GetName(), GetAge());
You have overcomplicated things. Read again the sources you are using to learn C to understand better what is going on.
Edited: Change your GetName() to:
void GetName(char *name){
printf("What is your name: ");
scanf("%s", name);
}
Now on main:
char name[31];
GetName(name);
printf("Your name is %s and your age is %d", name, GetAge());
The reason for that is that C can not return an array of characters (this is what you are trying to accomplish somehow). Instead, you can give that function the memory address of a local variable which lives in main() and store the user's input into that variable.
Upvotes: 2
Reputation: 1850
Try:
int GetAge()
{
int Age;
printf("What is your age: ");
if (scanf("%d", &Age) != 1)
return -1; // return an error code if an integer couldn't be read
return Age;
}
Now call the function using GetAge()
.
Upvotes: 0