我正在尝试使用这两个结构将结构返回到main,然后我将调用其他函数,如排序和打印。
我也得到error: request for member ‘vehicles’ in something not a structure or union
同样的错误,但error: request for member ‘count’ in something, not a structure or union
这些错误与
相对应value.count = count;
value.vehicles = vehicles;
这些是我正在使用的结构。
struct data{
char *model;
float engineSize;
int cost;
char *color;
};
struct values{
struct data vehicles;
int count;
};
这是将返回结构的排序readFile函数
struct values * readFile(){
FILE *fp;
int c;
int count = 0;
char *line = NULL;
size_t len = 0;
fp = fopen("hw3.data", "r");
while ((c = fgetc(fp)) != EOF){
if(c == '\n'){
count++;
}
}
if (feof(fp)){
rewind(fp);
struct data *vehicles = malloc((sizeof(struct data))* count);
count = 0;
char *token = NULL;
while (getline(&line, &len, fp)!= -1){
printf("%s", line);
token = strtok(line, " ");
vehicles[count].model = malloc(strlen(token) + 1);
strcpy(vehicles[count].model, token);
token = strtok(NULL, " ");
vehicles[count].engineSize = atof(token);
token = strtok(NULL, " ");
vehicles[count].cost = atoi(token);
token = strtok(NULL, " ");
vehicles[count].color = malloc(strlen(token) + 1);
strcpy(vehicles[count].color, token);
free(line);
line = NULL;
len = 0;
}
struct values *value = malloc(sizeof(struct values));
value.vehicles = vehicles;
value.count = count;
return value;
}
这是我将用于调用readFile函数,排序函数和打印函数的主要函数。
int main(){
int check = 1;
int input, n;
while (check == 1){
printf("Enter a value corresponding to a option on the menu below\n\n");
printf("1. Sort data by the float value & print high to low\n");
printf("2. Sort data by the float value & print low to high\n");
printf("3. Sort data by the int value & print high to low\n");
printf("4. Sort data by the int value & print low to high\n");
printf("5. Exit\n\n");
printf("Enter a value corresponding to the above menu\n");
scanf("%d", &input);
struct values *value = readFile();
struct data *vehicles = value.vehicles;
n = value.count;
if(input == 1 || input == 2 || input == 3 || input == 4 || input == 5){
if (input == 5){
exit(0);
}if (input == 1){
//sort float high to low
//bubbleSortFloats(vehicles[], 0);
}if (input == 2){
//sort float low to high
//bubbleSortFloats(vehicles[], 1);
}if (input == 3){
//sort int value high to low
//bubbleSortInts(vehicles[], 0);
}if (input == 4){
//sort int value low to high
//bubbleSortInts(vehicles[], 1);
}
}else{
printf("Enter a correct value for the menus above\n\n" );
}
}
}
答案 0 :(得分:2)
将是
value->vehicles = vehicles
value
是指向struct values
结构实例的内存的指针。首先取消引用指针以获取结构实例。编译器抱怨是因为你试图从一个既不是结构也不是联合的指针变量中获取vehicles
属性 - 它是一个指向struct values 实例的指针。其他成员value->count = count;
请注意,value->count
与(*value).count
相同。对此的简写表示法是箭头符号。 ->
。
value
- 是指向struct values
变量的指针。*value
- struct values
变量。(*value).count
- 是结构实例struct values
的成员变量。values->count
- 与最后一行相同。