5 Pointer and Function

1.1 Pointer and Function Parametric

1.1.1 General Reference

The essence of C language median value transfer is that when the called function is called, the called function will open up the same type of parameter space in its function stack and save the transferred value in the parameter space.

1.1.2 Delivery Address (Pointer)

There is no essential difference between a delivery address and a normal reference. Passing addresses and common parameters are both value passing, and arguments are either values or variables.

1.1.3 Transfer Value

There is no ordinary value transfer, because ordinary value transfer requires large parameter space and low efficiency, so only address transfer.

1.1.4 Transfer Structures

Four forms of data transmission:
(1) Membership value transfer
It is the transfer of ordinary values.
(2) Membership address transfer
(3) Transfer the whole structure
To transfer the whole structure as a common value, the shape parameters need to create the same size structure space for storing the transferred structure content.
(4) Address transfer of structure

1.2 Function Pointer

1.2.1 Function Pointer

Function pointer is actually a common variable. The type of common variable is the type of function pointer variable. Its value is the address of a function (that is, its function name is the corresponding value of the symbol in the compiler).

1.3 Calling Execution Function with Function Pointer

#include <stdio.h>
int add (int a, int b);
int sub (int a, int b);
int multiply (int a, int b);
int divide (int a, int b);

//Define a type pfunc, which points to a function with a specific parameter list and a return value
typedef int (*pfunc)(int, int);

int main(void)
{
pfunc p1 = NULL;
char c = 0;
int a= 0, b = 0 , result = 0;
printf("Please enter two integers to operate on:\n");
scanf("%d %d", &a, &b);

printf("Please enter the operation type:+ | - | * | / \n");
do
{
scanf("%c", &c);
}
while (c == '\n');
//Add a sentence of debugging
//printf("a = %d, b = %d, c =%d.\n",a , b, c)
switch (c)
{
case '+':
break;
case '-':
p1 = sub;
break;
case '*':
p1 = multiply;
break;
case '/':
p1 = divide;
break;
default:
p1 = NULL;
break;

}
result = p1 (a,b);
printf("%d %c %d = %d.\n", a , c ,b, result);

return 0;
}
int add(int a ,int b)
{
return a + b ;
}
int sub(int a ,int b)
{
return a - b;
}
int multiply(int a, int b)
{
return a * b;
}
int divide(int a ,int b )
{
return a/b;
}

Tags: C

Posted on Wed, 09 Oct 2019 01:57:48 -0700 by blyz