Simply you can find out whats wrong in your pointer manipulation by using your compiler warnings flags.
In windows and in Visual Studio IDE use built in debugger to see coding faults.
In linux environment on GCC compiler try compile your source code (in my case t.c
) with this command
gcc -Wall t.c -o t
gcc produce these warnings
t.c:8:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
func(int **y)
^
t.c: In function ‘func’:
t.c:11:8: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
*y = 1;
^
t.c:12:1: warning: control reaches end of non-void function [-Wreturn-type]
}
This is obvious that assignment *y = 1;
is wrong.
Thanks for Mark Benningfield for introduce useful link on using pointer to pointer
make change your code to some like this will solve your problem
#include <stdio.h>
int *p = NULL;
void func(int **y)
{
*y = malloc(sizeof(int));
**y = 1;
}
int main()
{
func(&p);
printf("%d\n",*p);
}
First for a function that not return any value use void as return type.
Second if we try to pass a pointer to pointer to a function as argument
for example func(int **y)
as y can hold address of a pointer
we must call it with func (&p)
. p
is a integer pointer.
At last this is recommended not to cast result of malloc()
with somethings like
(int *)malloc(sizeof(int))
cast the result of malloc?