C语言 错误:请求成员不是结构或联合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23168364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error: request for member in something not a structure or union
提问by user3551329
I'm having trouble with my code. My program is a program to simplify fractions. So my problem is this:
我的代码有问题。我的程序是一个简化分数的程序。所以我的问题是这样的:
I declare the structure Fraction. And then I declare structure Fraction f in my main function.
我声明了结构 Fraction。然后我在主函数中声明结构 Fraction f。
But when I try to use any member of the structure fraction (i.e. f.num, f.den) it says it's not a member of a structure or union. I have like 10 errors all saying the same thing for my program.
但是当我尝试使用结构分数(iefnum,f.den)的任何成员时,它说它不是结构或联合的成员。我有 10 个错误,都对我的程序说同样的话。
The error (verbatim): error: request for member "num" in something not a structure of union
错误(逐字逐句):错误:在非联合结构中请求成员“num”
#include <stio.h>
struct Fraction{
int num;
int den;
int lownum;//lownum = lowest numerator.
int lowden;//lowden = lowest denominator
int error;
};
void enter(struct Fraction *f);
void simplify(struct Fraction *f);
void display(const struct Fraction *f);
int main(void){
struct Fraction f;
printf("Fraction Simplifier\n");
printf("===================\n");
enter(&f);
simplify(&f);
display(&f);
}
void enter(struct Fraction *f){
printf("Please enter numerator : \n");
scanf("%d", &f.num);
printf("please enter denominator : \n");
scanf("%d", &f.den);
printf("%d %d", f.num, f.den);
}
void simplify(struct Fraction *f){
int a;
int b;
int c;
int negative; //is fraction positive?
a = f.num;
b = f.den;
if (a/b < 0){
negative = 1;
}
if(b == 0){
f.error = 1;
}
if(a < 0){
a = a * -1;
}
if(b < 0){
b = b * -1;
}
//euclids method
if(a < b){
c = a;
a = b;
b = c;
}
while(b != 0){
c = a % b;
a = b;
b = c;
}
f.lownum = f.num / a;
f.lowden = f.den / a;
if(negative = 1){
f.lownum = f.lownum * -1;
}
}
void display (const struct Fraction *f){
if (f.error != 1){
printf("%d / %d", f.lownum, f.lowden);
}else{
printf("error");
}
}
回答by Martin R
In
在
void simplify(struct Fraction *f)
fis a pointerto struct Fraction. Therefore, instead of
f是一个指针到struct Fraction。因此,代替
a = f.num;
you have to write
你必须写
a = (*f).num;
which can be shortened to the equivalent notation:
可以缩短为等效符号:
a = f->num;
The same applies to all other references to struct Fraction *fin your functions.
这同样适用struct Fraction *f于您的函数中的所有其他引用。
回答by ju.kreber
You use a pointer (struct Fraction *f). So you have to acces members with the -> operator:
你使用一个指针(struct Fraction *f)。因此,您必须使用 -> 运算符访问成员:
f->num

