Reputation: 199
I have been trying to pass a struct as an argument, but I seem to have an issue with the different structs. My goal is to create a generic function that takes a struct and then overwrites a field in particular struct.
struct information{
int number;
};
typedef struct information Jack;
typedef struct information Joe;
and then a function.
foo(struct information Name , int randomNumber) {
Name.number = randomNumber;
}
However, when I print Jack.number and Joe.number, it prints 0.
void main() {
int h =5;
foo(Joe,h);
foo(Jack,h);
printf("%d",Jack.number);
printf("%d",Joe.number);
}
Is there any way of solving this issue and create such a generic function?
Upvotes: 0
Views: 2910
Reputation: 1000
Remember that C passes, values to function and not reference. So as everyone has mentioned,you could pass the address of the structure(which you want to modify) to the function and then the changes made to the structure inside that function would be automatically reflected in main function.
Upvotes: 0
Reputation: 438
Perhaps you should pass a pointer to your struct, like this:
foo(struct information *Name , int randomNumber) {
Name->number = randomNumber;
}
You would call your function like this:
foo (&Jack, 42);
[Edit] Oh, and there's something wrong with your declarations as well. Maybe you could declare your objects like this:
typedef struct informationStruct {
int number;
} Information;
Information Jack;
Information Joe;
and your function like this:
foo(Information *Name , int randomNumber) {
Name->number = randomNumber;
}
Upvotes: 2
Reputation: 206737
You are passing the struct
by value. Whatever changes you make to Name
in foo
affects only the copy of the object in foo
. It does not change the value of the object in the calling function.
If you want the change to take effect in the calling function, you'll need to pass a pointer to it. For that, you'll need to change the interface of foo
.
foo(struct information* Name , int randomNumber) {
Name->number = randomNumber;
}
You'll need to change the call also to match the interface.
foo(&Joe,h);
foo(&Jack,h);
Upvotes: 1
Reputation: 81878
C passes structs by value (as every other argument type). If you want to see changes outside of the function, pass it by reference:
void foo(struct information *name, int randomNumber) {
name->number = randomNumber;
}
foo(&joe, 42);
Upvotes: 1