Originally Posted by Beginner_in_C
My problem is I dont see any difference if r is passed as the struct or as pointer. Whats the problem if I will pass as the struct?? Can anyone explain please???
You don't see the difference? Really? Have you tried to display the contents of the struct after making that function call using a struct instead of a pointer to the struct? Do you see the changes you had made to it in the function?
Here's a quick test program that illustrates what happens:
void WithPointer(struct Beispiel *r, int n, const char *s);
void WithoutPointer(struct Beispiel r, int n, const char *s);
struct Beispiel record;
record.num = 1;
printf("Initial values: %d, %s\n", record.num, record.label);
WithoutPointer(record, 2, "Label2");
printf("After call without pointer: %d, %s\n", record.num, record.label);
WithPointer(&record, 3, "Label3");
printf("After call with pointer: %d, %s\n", record.num, record.label);
void WithPointer(struct Beispiel *r, int n, const char *s)
r->num = n;
void WithoutPointer(struct Beispiel r, int n, const char *s)
r.num = n;
Here is what the program outputs:
| Initial values: 1, Label1 |
After call without pointer: 1, Label1
After call with pointer: 3, Label3
Do you see the difference now? Just passing the struct keeps the changes inside the function, while passing a pointer to the struct changes the struct itself.
Here's why. When you pass an argument to a function, the program evaluates the argument (which in the case of a variable is reading its value) and then copies
that value to the function. Always. That means that what the function is using and changing is not the variable you passed to it, but rather a copy of that variable
. So none of the changes that the function makes can affect the original variable at all, since it's only a copy
that's being changed. And when you return from the function, those copied arguments go away, cease to exist.
One type of variable you can pass to a function is a pointer. Yes, the function only gets a copy of that pointer to use, but that copy still points to where the original pointer did. Now when the function uses that pointer to change where it's pointing to, it's the original variable being pointed to that is changed. And when you return from that function, those changes still exist.
So if you pass a struct, the function just gets a copy of that struct and the changes you make to it inside the function go away. But if you pass a pointer to the struct, the original struct itself is changed and those changes continue to exist even after you return from the function.
Does that make sense?