The same question:
What will be the output of the following C code?
Question 1:
// Date:2020/3/29
// Author:xiezhg5
#include <stdio.h>
void foo(int*);
int main(void)
{
int i=10,*p=&i;
foo(p++);
}
void foo(int*p)
{
printf("%d\n",*p);
}
//Answer: 10
Question 2:
// Date:2020/3/29
// Author:xiezhg5
#include <stdio.h>
void foo(int *p);
int main(void)
{
int i=97,*p=&i;
foo(&i);
printf("%d\n",*p);
}
void foo(int *p)
{
int j=2;
p=&j;
printf("%d ",*p);
}
//Answer:2 97
Question 3:
// Date:2020/3/29
// Author:xiezhg5
#include <stdio.h>
void foo(int **p);
int main(void)
{
int i=97,*p=&i;
foo(&p);
printf("%d\n",*p);
return 0;
}
void foo(int **p)
{
int j=2;
*p=&j;
printf("%d ",**p);
}
//Answer:2 2
Question 4:
// Date:2020/3/29
// Author:xiezhg5
#include <stdio.h>
void foo(int **p);
int main(void)
{
int i=10;
int *const p=&i;
foo(&p);
printf("%d\n",*p);
}
void foo(int **p)
{
int j=11;
*p=&j;
printf("%d ",**p);
}
//Answer:11 11
Question 5:
// Date:2020/3/29
// Author:xiezhg5
#include <stdio.h>
void foo(int **p);
int main(void)
{
int i=10;
int *p=&i;
foo(&p);
printf("%d ",*p);
printf("%d ",*p);
}
void foo(int **const p)
{
int j=11;
*p=&j;
printf("%d ",**p);
}
//Answer:11 11 Undefined-value
Pointers to functions
A pointer to function can be initialized with an address of a function. Because of the function-to-pointer conversion, the address-of operator is optional:
void f(int);
void (*pf1)(int) = &f;
void (*pf2)(int) = f; // same as &f
Unlike functions, pointers to functions are objects and thus can be stored in arrays, copied, assigned, passed to other functions as arguments, etc.
A pointer to function can be used on the left-hand side of the function call operator; this invokes the pointed-to function:
#include <stdio.h>
int f(int n)
{
printf("%d\n", n);
return n*n;
}
int main(void)
{
int (*p)(int) = f;
int x = p(7);
}
Dereferencing a function pointer yields the function designator for the pointed-to function:
int f();
int (*p)() = f; // pointer p is pointing to f
(*p)(); // function f invoked through the function designator
p(); // function f invoked directly through the pointer
Equality comparison operators are defined for pointers to functions (they compare equal if pointing to the same function).
Because compatibility of function types ignores top-level qualifiers of the function parameters, pointers to functions whose parameters only differ in their top-level qualifiers are interchangeable:
int f(int), fc(const int);
int (*pc)(const int) = f; // OK
int (*p)(int) = fc; // OK
pc = p; // OK