
Originally Posted by
Dadu@
I am doing experiements with code to understand pointer
Code:
#include <stdio.h>#include <stdlib.h>
void foo ( int *p)
{
int *q = malloc(sizeof(*q));
if ( q != NULL )
{
}
}
int main ()
{
int *p = NULL;
foo (p);
return 0;
}
This code compile without warning. Program pass the content of pointer p
When I change line to pass location of pointer variable P I get warnings
warnings
Code:
hello.c:17:8: warning: passing argument 1 of 'foo' from incompatible pointer type [-Wincompatible-pointer-types] foo (&p);
^
hello.c:4:6: note: expected 'int *' but argument is of type 'int **'
void foo ( int *p)
I want to understand why this warning generates and why it resolve by declearing double pointer
Please study the code below, that hopefullly will explain the error message you received:
Code:
#include <stdio.h>
// foo() is a function that takes a pointer to an int, or simply,
// the address of an int, passed by value
void foo(int *p); // I always prototype all my functions
int main(void)
{
int a = 123; // Always initialize all your local variables,
// to some legitimate value, or 0!
// ptr is a pointer varaible that will contain the address
// of an int, in this case, the address of the variable, a.
int *ptr = &a;
printf("Address of a: %p\n", (void *)&a);
printf(" Value of a: %d\n\n", a);
printf("Address of ptr: %p\n", (void *)&ptr);
printf(" Value of ptr: %p\n\n", (void *)ptr);
// foo() may be called passing the address of a. An int *
foo(&a);
// Or foo() may be call with the pointer, ptr, or the address
// value containd within ptr, the address of a, Also an int *
foo(ptr);
// foo() may NOT be called with "&ptr"!!!
// You are attempting to pass the address of ptr, NOT the
// address contained within ptr! &ptr is a int **,
// A pointer to a pointer to an int!!! Which explains the
// warning message yopur received.
// foo(&ptr);
return 0;
}
void foo(int *p)
{
printf("Inside foo(), Address of the local variable, p: %p\n", (void *)&p);
printf("Inside foo(), Address passed through p: %p\n", (void *)p);
printf("Inside foo(), Value of value pointed to by p: %d\n\n", *p);
}
You really need to study one of the three books I recommended to you earlier. A good up-to-date book on C will thoroughly explain pointers, the most difficult topic in learning C, along with so much more that you need to program in C! I can't emphasize this enough!