While learning about structs, I came across this question: Initialize/reset struct to zero/null. I then wondered if using a function that returned a struct would work for changing a struct. The following code is a working example I've tested:
#include <stdio.h>
struct location {
int x, y;
};
struct location move1(struct location);
void move2(struct location *);
int main(void)
{
struct location loc1 = {0};
struct location loc2 = {0};
/* first method */
printf("x %d, y %d\n", loc1.x, loc1.y);
loc1 = move1(loc1);
printf("x %d, y %d\n", loc1.x, loc1.y);
/* second method */
printf("x %d, y %d\n", loc2.x, loc2.y);
move2(&loc2);
printf("x %d, y %d\n", loc2.x, loc2.y);
return 0;
}
struct location move1(struct location loc)
{
loc.x = 2;
loc.y = 3;
return loc;
}
void move2(struct location *loc)
{
loc->x = 4;
loc->y = 5;
}
My specific question is this: Is there anything wrong with the first method? And if not, is there any reason to prefer one method over the other?
Also note, I am adhering to C90. I have not yet learned about compound literals, etc.