我在c中找出结构,但不确定为什么不返回值。我知道当您将一个函数传递给数组并添加值时,这些值将在函数之后的数组中。结构也是如此吗?以下是我的代码的简化版本(我的结构具有更多内部变量,但也未返回)。
typedef struct {
double points;
FILE *file;
} Polygon;
void readobject(FILE *g, Polygon poly) {
fscanf(g, "%lf", &poly.points); //lets say this is reads in 6.0
printf("%lf\n", poly.points); //this will print 6.0
}
int main (int argc, char **argv){
Polygon polygon[argc];
int cc = 0;
polygon[cc].file = fopen(argv[cc], "r");
readobject(polygon[cc].file, polygon[cc]);
printf("%lf\n", polygon[cc].points); //This prints out 0.0
}
为什么这样做呢?我怎样才能使它返回6.0?
最佳答案
您正在按值将对象传递给readobject
。 readobject
中的修改是该功能的本地内容。您需要传递一个指向该对象的指针,以使更改从main
可见。
void readobject(FILE *g, Polygon* poly) {
// ^^
fscanf(g, "%lf", &(poly->points)); //lets say this is reads in 6.0
printf("%lf\n", poly->points); //this will print 6.0
}
然后使用以下命令致电:
readobject(polygon[cc].file, &polygon[cc]);
// ^^