R
ritesh
Hi,
I'm unable to figure out why initializing a pointer dosen't work this
way -
void func(int * x)
{
x = (int*)(malloc(sizeof(int*)));
*x = 2;
}
int main(void)
{
int * a = 0;
func(a);
printf(" value of a = %d" , *a); /* getting SEGV fault here */
}
buf works this way -
void func(int ** x)
{
*x = (int*)(malloc(sizeof(int*)));
**x = 2;
}
int main(void)
{
int * a = 0;
func(&a);
printf(" value of a = %d" , **a); /* Prints 2 */
}
Could someone please explain this in detail.
Shouldn't the first code example work fine
1. I'm passing a pointer to a function
2. which intializes it
3. and assigns a value to the location pointed to by this pointer
4. Running this in a debugger shows that in main() 'a' hasn't been
intialized even after the call to func()
The second example works fine.
Thanks,
Ritesh
I'm unable to figure out why initializing a pointer dosen't work this
way -
void func(int * x)
{
x = (int*)(malloc(sizeof(int*)));
*x = 2;
}
int main(void)
{
int * a = 0;
func(a);
printf(" value of a = %d" , *a); /* getting SEGV fault here */
}
buf works this way -
void func(int ** x)
{
*x = (int*)(malloc(sizeof(int*)));
**x = 2;
}
int main(void)
{
int * a = 0;
func(&a);
printf(" value of a = %d" , **a); /* Prints 2 */
}
Could someone please explain this in detail.
Shouldn't the first code example work fine
1. I'm passing a pointer to a function
2. which intializes it
3. and assigns a value to the location pointed to by this pointer
4. Running this in a debugger shows that in main() 'a' hasn't been
intialized even after the call to func()
The second example works fine.
Thanks,
Ritesh