I have modified some tutorial code to get input from the keyboard, and then call a function with a pointer to a structure as input.
I have got it working but I don't understand why the first time I tried it it didn't work, it only worked when I used & in scanf for the integer of age.
Code:
#include <stdio.h>
#include <string.h>
struct tag{ /* the structure type */
char lname[20]; /* last name */
char fname[20]; /* first name */
int age; /* age */
float rate; /* e.g. 12.75 per hour */
};
struct tag my_struct; /* define the structure */
void show_name(struct tag *p); /* function prototype */
int main(void)
{
struct tag *st_ptr; /* a pointer to a structure */
st_ptr = &my_struct; /* point the pointer to my_struct */
printf("\n What is your first name?");
scanf("\n %s", st_ptr->fname);
printf("\n What is your surname?");
scanf("\n %s", st_ptr->lname);
printf("\n What is your age?");
scanf("\n %d", &my_struct.age);
show_name(st_ptr); /* pass the pointer */
/* return 0; */
}
void show_name(struct tag *p)
{
printf("\n %s ", p->fname); /* p points to a structure */
printf(" \n %s ", p->lname);
printf("%d\n", p->age);
}
In red, if I try without the & it gives me:
pointerstruct.c: In function ‘main’:
pointerstruct.c:24: warning: format ‘%d’ expects type ‘int *’, but argument 2 has type ‘int’
I know for scanf the & is not necessary for fname and lname as they are arrays and have constant pointers to the first element of the array anyway. But with the age I can't see why I get this message when use st_ptr->age, as I am using a pointer to the address at my_struct, which is what the error message is complaining of, it wants an address, but I am giving it an address.
Also I have seen in tutorials that they use st_ptr->age or my_struct.age without the & in scanf.