The error is referencing the following line of code:
tenant[i].name = get_string("Enter the residents name: ");
and has an arrow pointing at the period . between tenant[i] and name. I am not sure what I am missing.
typedef struct {
string name;
int apt;
} tenant;
int n;
int numres(void);
string nameres(int numres);
int apt(int numofres);
int main(void) {
int numres(void);
tenant tenants[n];
string nameres(int n);
int apt(int n);
for (int m = 0; m < n; m++) {
printf("Resident %s resides in apt# %i\n",
tenants[m].name, tenants[m].apt);
}
return 0;
}
//this function prompts the user for the number of residents
int numres(void) {
do {
n = get_int("Enter the number of residents: ");
} while (isalpha(n) != 0 || isspace(n) != 0);
return n;
}
// this function prompts the user for the residents names.
string nameres(int numres) {
int i = 0;
do {
tenant[i].name = get_string("Enter the residents name: ");
return tenant[i].name;
i++;
} while (i < numres);
}
// this function prompts the user for the residents apt number
int apt(int numofres) {
for (int i = 0; i < numofres; i++) {
tenant[i].apt = get_int("Enter residents apt number: ");
return tenant[i].apt;
}
}
There are multiple problems in the code:
the
stringtype is not a standard C type, it is defined in<cs50.h>as atypedefforchar *, which can be quite confusing. Make sure you include<cs50.h>and<stdio.h>.in the
mainfunction, you definetenant tenants[n];, an array with a length specified by a variable that has a value of0: this has undefined behavior, and the array cannot be used for anything.in the
mainfunction, you declare functionsint numres(void);,string nameres(int n);andint apt(int n);. Such declarations should be made at the file scope, and indeed are done so already. You probably meant to call the functions instead, so you should write:But passing the value of
nas a global variable is cumbersome and confusing.numres()should return the value andnshould be a local variable.in
numres, it does not make sense to testisalpha(n) != 0 || isspace(n) != 0becausenis a number, not the value of a byte read from the input stream. The functionget_intalready checks for valid input and returns a converted number, you should just check that the number is positive:n > 0.nameresshould be defined as avoidfunction and use aforloop for the case wherenhas the value0.in
nameresandaptshould receivetenantsas an argument as this array is defined locally inmain. The code should usetenantsinstead oftenant, which is a type name. This is the reason for your compilation issue. Using a_tsuffix for the types is recommended to avoid such problems.in
nameresandaptshould should prompt for the name and apartment numbers of all residents, remove thereturnstatements.using
whileorforloops instead ofdo/whileloops allows for more concise code with explicit tests closer to the generating fact.Here is a modified version: