I am learning C. I was writing code to create a linked list when i came across a segmentation fault. I found a solution to my problem in this question. I was trying to pass a pointer by reference. The solution says that we can't do so. We have to pass a pointer to a pointer. This solution worked for me. However, I don't understand why is it so. Can anyone tell the reason?
From The C Programming Language - Second Edition (K&R 2):
5.2 Pointers and Function Arguments
Since C passes arguments to functions by value, there is no direct way for the called function to alter a variable in the calling function.
...
Pointer arguments enable a function to access and change objects in the function that called it.
If you understand that:
void fn1(int x) {
x = 5; /* a in main is not affected */
}
void fn2(int *x) {
*x = 5; /* a in main is affected */
}
int main(void) {
int a;
fn1(a);
fn2(&a);
return 0;
}
for the same reason:
void fn1(element *x) {
x = malloc(sizeof(element)); /* a in main is not affected */
}
void fn2(element **x) {
*x = malloc(sizeof(element)); /* a in main is affected */
}
int main(void) {
element *a;
fn1(a);
fn2(&a);
return 0;
}
As you can see, there is no difference between an int
and a pointer to element, in the first example you need to pass a pointer to int
, in the second one you need to pass a pointer to pointer to element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With