-
Using Unions
I've got to write a program that will allow a user to create a contact book that holds multiple peoples' name, age, and either school name, salary, or year of retirement, depending on the age. I've got to use structures for the first two and a union for the latter. Here is a portion of my code:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int counter = 0;
void stars(void);
void insert(void);
void show(void);
typedef union{
char schoolName[20];
float salary;
int year;
} status;
typedef struct{
char name[20];
int age;
status personInfo;
} info;
struct info person;
...
void insert(void)
{
union status *q;
q = &personInfo;
struct info *p;
p = person;
char input[20];
printf("Enter name:\n");
scanf("%s", input);
strcpy(person[counter].name, input);
printf("Enter age:\n");
scanf("%d", &person[counter].age);
if(person[counter].age <= 21)
{
printf("Enter school name:\n");
scanf("%s", input);
strcpy(personInfo[counter].schoolName, input);
}
else if (person[counter].age < 65 && person[counter].age > 21)
{
printf("Enter salary per month:\n");
scanf("%f", personInfo[counter].salary);
}
else
{
printf("Enter year of retirement:\n");
scanf("%d", personInfo[counter].year);
}
printf("Your name, %s, and age, %d, have been added.\n", person[counter].name, person[counter].age);
counter++;
return;
}
It keeps telling me that 'personInfo' is undeclared in the insert function. How do I fix this?
-
Code:
void insert(void)
{
union status *q;
q = &personInfo;
You do not have anything called 'personInfo'. You would need to make something like:
Code:
info x;
q = &x.personInfo;
This is also wrong:
Code:
typedef struct{
char name[20];
int age;
status personInfo;
} info;
struct info person;
Or at least I don't think it's doing what you think it's doing. You are declaring a variable named 'person' of type 'struct info', of which there is no such thing, because your typedef is an unlabeled structure typedeffed to 'info'. So if you were actually trying to declare an instance of 'info', you would do:At which point in time you could then do:
Code:
q = &person.personInfo;
What should you take away from this? Typedefs are most of the time more confusing than good.
Quzah.