Reputation: 794
I'm figuring out structs in c and I'm not sure why this is not returning with values. I know that when you pass a function an array, and add values, the values are in the array after the function. Is this true for structs as well? Below is a simplified version of my code (my structs have more internal variables, but they are not being returned either).
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
}
Why does this do that? How can I get it to return 6.0?
Upvotes: 0
Views: 2368
Reputation: 709
While the data is stored next to each other in memory with structs just like with arrays, structs differ from arrays because you can have values (members) of different types in it. If you'd like to have your value be modified, then you either pass its pointer or by reference.
As a pointer:
void readobject(FILE *g, Polygon *poly) {
//since its a pointer, you access the object's members by the '->' operator
fscanf(g, "%lf", &poly->points);
printf("%lf\n", poly->points); //this will print 6.0
}
//call
readobject(polygon[cc].file, &polygon[cc]);
By reference:
void readobject(FILE *g, Polygon &poly) {
// you can use the '.' operator normally with references
fscanf(g, "%lf", &poly.points);
printf("%lf\n", poly.points); //this will print 6.0
}
//call
readobject(polygon[cc].file, polygon[cc]); //we pass the actual object
Upvotes: 0
Reputation: 206607
You are passing the object by value to readobject
. The modification in readobject
are local to the function. You need to pass a pointer to the object to make the change visible from 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
}
and then call using:
readobject(polygon[cc].file, &polygon[cc]);
// ^^
Upvotes: 1