int *ptr;
is a pointer to an interger, but you never initialized it. The value of ptr
is not defined so this is undefined behavior. To make your code work, the value of ptr
has to be an address of a variable with type int
. *ptr
and **p_ptr
tries to read the value where ptr
refers to and this causes the segmentation fault. Adapt your code like this:
main()
{
int myInt; // local varibale myInt
int *ptr = &myInt; // pointer ptr refers to local varibale myInt
init(&ptr); // pass pointer to ptr to function init
printf(" %d \n",*ptr);
}
Note in function init
, p_ptr
now is a pointer to ptr
and so a pointer to a pointer to myInt
.
Of course you can allocate dynamic memory too:
#include <malloc.h>
main()
{
int *ptr = &myInt = malloc( sizeof( int ) ); // ptr refers to dynamicly allocated memory
init(&ptr);
printf(" %d \n",*ptr);
free( ptr ); // free the dynamic memory
}
solved Segmentaion fault in C