I whipped up some short code to try an learn more about structures, pointers and functions and argument passing. I am not a total newbie, but still learning. I wrote this up so maybe we can use it to learn and talk about these issues.
My real question is concerning passing a pointer to a structure within a function argument.Code:#include <stdio.h> #include <string.h> struct person{ char name[25]; int age; } john; // this is just a random name not mine! void person_init(struct person *human, int agenum, char *name); int getAge(struct person *human); char* getName(struct person *human); int main(){ person_init(&john, 24, "Johnny"); getName(&john); getAge(&john); printf("\nHis name is certainly, %s\n", getName(&john)); // Pointless, just testing return value return 0; } void person_init(struct person *human, int agenum, char *name){ strcpy(human->name, name); human->age = agenum; } int getAge(struct person *human){ printf("\nThe person is %d years old.\n", human->age); return human->age; } char* getName(struct person *human){ printf("The person's name is %s", human->name); return human->name; }
Typically when you pass a pointer to a variable into a function you pass the base address. For example
My question here is concerning the structure. Why does the structure require the & for the base address? It seems like a peculiar point because it doesn't seem to abbly to many other data structures... not arrays or functions. So why then does the structure require it? Shouldn't a structure be able to be bassed simply by statingCode:void function(int *ptr); // This is the fun function(ptr_add); // this is what it would look like when you called it in main
Not to mention when you declared the struct you didn't declare a pointer to it, you declared it as a standard struct but the argument treats it as a pointer to a structure. What's up with that?Code:getName(john); // but this is wrong... requires &
Any thoughts?



LinkBack URL
About LinkBacks



