I have an array of structures:
struct city cities[100];
I want to place two "instances" of that struct array into a method that computes a distance:
double compute_distance(city cities[] x, city cities[] y) {
/* some code here */
}
This method is wrong. How do I get it to work?
C struct array question?
If you want to pass two arrays to the function, then change the following line:
double compute_distance(city cities[] x, city cities[] y)
To:
double compute_distance(struct city x[ ], struct city y[ ])
If you want to pass two instanses to the function change the previous line to:
double compute_distance(struct city x, struct city y)
To call the function within main, all you have to do is the following:
double distance = 0.0;
int a = 0; // change this to the index of the 1st. city
int b = 0; // change this to the index of the 2nd city
distance = compute_distance(cities[ a ], cities[ b ]);
Reply:Hi,
You have one array, with 100 "instances" of the city struct in it, so I think you mean that you want to call the compute_distance function with two cities from the array. You could do this just making the parameters of type "struct city", but that would make a copy of each city for the procedure - with two side effects:
1) If you make changes to either city inside the function, they're not made to the copies in the array, and
2) It takes time and memory to make copies.
So I recommend using pointers as the parameters, like this:
double compute_distance(struct city * x, struct city * y)
{
/* some code here */
}
Then you use x-%26gt;some_field style syntax inside the function.
Call the function using the %26amp; operator to get a pointer to a certain city. For example, to call compute_distance with the 5th and 8th cities:
distance = compute_distance(%26amp;cities[4], %26amp;cities[7]);
Good luck!
petal
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment