Hello, all...
So, I am brand-spankin' new to C, and I am doing the few lessons for beginners on Learn-C.org, and I came to a lesson about using pointers to show a function where the variable is located instead of passing the value of the variable itself, I guess/I think.
Anyway, during the practice problem, which was "Write a function called birthday, which adds one to the age of a person." I solved the missing portion from the provided code and hit run, and it cleared. It was one of the first questions that seemed a bit more in depth, and being that I've been learning some languages like Python and SQL/R for about a year or so, obviously, there's usually more than one way to solve a problem. So, just out of curiosity, instead of moving on to the next lesson, I returned and clicked the "Show Solution" button. and was actually a bit surprised, all things considered, the main being I don't at all what I'm doing.
Sorry, I'm rambling... Which of these two chunks of code is more efficient, and why?
Code:
"""
Code segment from Learn-C
"""
#include <stdio.h>
typedef struct {
char * name;
int age;
} person;
/* function declaration */
void birthday(person * p);
void birthday(person * p){
(*p).age += 1;
}
int main() {
person john;
john.name = "John";
john.age = 27;
printf("%s is %d years old.\n", john.name, john.age);
birthday(&john);
printf("Happy birthday! %s is now %d years old.\n", john.name, john.age);
return 0;
}
Code:
"""
Code segment I completed
"""
#include <stdio.h>
typedef struct {
char * name;
int age;
} person;
/* function declaration */
void birthday(person * p) {
(*p).age++;
}
int main() {
person john;
john.name = "John";
john.age = 27;
printf("%s is %d years old.\n", john.name, john.age);
birthday(&john);
printf("Happy birthday! %s is now %d years old.\n", john.name, john.age);
return 0;
}
The bit under "/* Function Declaration */" is obviously where the difference is.
Again, I would just like to know which way you would do it and why? Or is this just a fluke and the way the program grades the user solutions was somehow glitched out and just happened to allow my solution? All responses would be greatly appreciated... Thank you in advance...
Take it easy...
-Chrisg8691
PS I went throught the trouble of going to look up how to embed a url link into this post, because though I've been on forums looking for answers since I started trying to learn how to code, I'm new to actually posting to forums, and haven't embedded a link since I was like ten, messing around on Myspace. But I go through all that trouble only to scroll down and find out that it does it automatically. FAIL!