Here
struct temp * var2 = NULL;
you create a pointer to struct temp
and initialize it to NULL. It is only a pointer - there is not any memory for a struct temp
.
Then you do:
var2->a = 10;
which means you dereference a NULL pointer. That will fail.
Try this:
struct temp * var2 = malloc(sizeof *var2); // Create pointer and allocate
// memory for a struct temp
instead.
BTW: You don't need to pass double-pointer to the function. Just int pass(struct temp *);
will do.
So the complete code could be:
#include <stdio.h>
#include <stdlib.h>
struct temp {
int a;
};
int pass(struct temp *); //passing var
int pass(struct temp * var1) { //passing var
var1->a = 100;
return 0;
};
int main() {
struct temp * var2 = malloc(sizeof *var2);
var2->a = 10;
printf("\nbefore pass var2->a = %d", var2->a);
pass(var2);
printf("\nafter pass var2->a = %d", var2->a);
free(var2);
return 0;
}
Passing a double pointer in code like this is only needed if you want to change the value of var2
in main. For instance if the function should allocate more memory (i.e. more struct temp
elements).
It could be like:
#include <stdio.h>
#include <stdlib.h>
struct temp {
int a;
};
int pass(struct temp **);
int pass(struct temp ** var1) {
free(*var1); // Free previous allocation
*var1 = malloc(20 * sizeof **var1); // Allocate 20 struct temp
(*var1)[0].a = 100;
(*var1)[1].a = 200;
return 0;
};
int main() {
struct temp * var2 = malloc(sizeof *var2); // Allocate 1 struct temp
var2->a = 10;
printf("\npointer before pass var2 = %p", (void*)var2);
printf("\nbefore pass var2[0].a = %d", var2[0].a);
// printf("\nbefore pass var2[1].a = %d", var2[1].a); // ILLEGAL HERE
pass(&var2);
printf("\npointer after pass var2 = %p", (void*)var2);
printf("\nafter pass var2[0].a = %d", var2[0].a);
printf("\nafter pass var2[1].a = %d", var2[1].a); // LEGAL HERE
free(var2);
return 0;
}
Possible output:
pointer before pass var2 = 0x563d28afa010
before pass var2[0].a = 10
pointer after pass var2 = 0x563d28afb040
after pass var2[0].a = 100
after pass var2[1].a = 200
Notice how the value of the pointer changed.