I'm trying to get a deeper understanding on pointer arguments in functions for C. I've written a test program to try to see the difference between passing a single pointer vs a double pointer to a function and then modifying it.
I have a program that has two functions. The first function modifyMe1
takes a single pointer as an argument and changes the a property to 7. The second function modifyMe2
takes a double pointer as an argument and changes the a property to 7.
I expected that the first function modifyMe1
, would be "pass-by-value" that is if I passed in my struct pointer, C would create a copy of the data pointed by it. While with the latter, I am doing a "pass-by-reference" which should modify the structure in place.
However, when I test this program out, both functions seem to modify the structure in place. I know there is a misunderstanding for me on the nature of pointers are arguments for sure. Can someone help clear this up for me?
Thanks!
Here is what I have:
#include <stdio.h>
#include <stdlib.h>
struct myStructure {
int a;
int b;
};
void modifyMe1(struct myStructure *param1) {
param1->a = 7;
}
void modifyMe2(struct myStructure **param1) {
(*param1)->a = 7;
}
int main(int argc, char *argv[]) {
struct myStructure *test1;
test1 = malloc(sizeof(test1));
test1->a = 5;
test1->b = 6;
modifyMe1(test1);
printf("a: %d, b: %d\n", test1->a, test1->b);
// set it back to 5
test1->a = 5;
printf("reset. a: %d, b: %d\n", test1->a, test1->b);
modifyMe2(&test1);
printf("a: %d, b: %d\n", test1->a, test1->b);
free(test1);
return 0;
}
In which my output is:
$ ./a
a: 7, b: 6
reset. a: 5, b: 6
a: 7, b: 6
void foo(int *p) { p = malloc(size); }
. – Mandate