Already this question is been asked here: double pointer vs single pointer
I followed the instructions of this above question but facing segfaults and still unable to understand exactly whats happening in the memory (what points to what and how). Below is the code:
#include <stdio.h>
#include <stdlib.h>
void func(int **ptr)
{
*ptr = (int *) malloc (sizeof(int));
**ptr = 10;
printf("Inside func: ptr: %p *ptr: %p **ptr: %p %d\n", ptr, *ptr, **ptr, **ptr);
}
void func2(int *ptr)
{
int i = 10;
ptr = (int *) malloc (sizeof(int));
*ptr = 288;
printf("Inside func2: ptr: %p *ptr: %p %d\n", ptr, *ptr, *ptr);
}
int main()
{
int *a = NULL, *b = NULL;
func(&a);
printf("&a: %p, a: %p, *a: %p *a: %p %d\n", &a, a, *a, *a, *a);
func2(b);
printf("*b: %d\n", *b);
return 0;
}
Output:
main.c:8:51: warning: format ‘%p’ expects argument of type ‘void *’, but argument 4 has type ‘int’ [-Wformat=]
main.c:16:42: warning: format ‘%p’ expects argument of type ‘void *’, but argument 3 has type ‘int’ [-Wformat=]
main.c:23:33: warning: format ‘%p’ expects argument of type ‘void *’, but argument 4 has type ‘int’ [-Wformat=]
main.c:23:40: warning: format ‘%p’ expects argument of type ‘void *’, but argument 5 has type ‘int’ [-Wformat=]
Inside func: ptr: 0x7ffcf5c49760 *ptr: 0x22f7010 **ptr: 0xa 10
&a: 0x7ffcf5c49760, a: 0x22f7010, *a: 0xa *a: 0xa 10
Inside func2: ptr: 0x22f7030 *ptr: 0x120 288
Segmentation fault (core dumped)
In func--> when a & ptr
are assigned & pointing to same memory locations, why cant it happen to func2.
Anyways for *ptr I am passing b (which is the address of *b) and changing the value.
Unable to understand what points to what and how. If someone could help will be very thankful.
Though its a repetition of already asked question, posted since the answer is insufficient for me to understand. Hence pls dont mark is as duplicate atleast until the question is been answered correctly.