I am a beginner at C, I have a program where I’m trying to set values of a structure inside a function, but I’m unsure of how to pass the structure to the function and have it modify it’s original values.
I have a simple structure that looks like this:
struct player {
char name[40];
int acceleration;
};
And just to play around I do this:
struct player terry;
terry.acceleration = 20;
strcpy(terry.name, "John Terry");
I want to move this functionality to a function so I can do something like this:
createPlayer(terry, 20, "John Terry");
So far my function looks like this:
void createPlayer(struct player currentPlayer, char name[], int acceleration) {
strcpy(currentPlayer.name, name);
currentPlayer.acceleration = acceleration;
}
But when I print this:
printf("The speed of %s is %d \n\n", terry.name, terry.acceleration);
I see this:
The speed of is 0
What am I doing wrong here? Please suggest any changes to my code / style that goes against the usual convention.
Thank you so much!
You’ll need to pass the struct by pointer:
Change the function to this:
And call it like this:
EDIT:
In your original code, when you pass the struct into the function. It is done “by value”. This means that a copy is made into the function. So what changes you make to it inside the function will be on the local copy and will not be applied to the original copy.