question:
Write an auto-increment function that increments by 1 each time it is called.
Idea:
- It means that the function I wrote either affects the value of the main function to achieve self-increment by 1. Or, returns a value and then adds it up in the main function.
- That is, one passes the address to the function and the other passes the value.
- Passing the address means that the formal parameter can access the main function through the address of the actual parameter, thereby affecting the value of the actual parameter.
- Passing a value is just a temporary copy of the formal parameter to the actual parameter, that is, they are two storage spaces, and the mixing does not affect it, just like copying and pasting.
- Here we mainly introduce the transfer address.
- The actual parameter needs to use the & address character to pass the address of the actual parameter to the formal parameter. In the function, the formal parameter needs to define a pointer variable to receive the address of the actual parameter.
- In a function, when incrementing, you need to use the * symbol, which is a content-retrieving symbol. It is also used when defining a pointer. However, when declaring a pointer, it means that the pointer is not fetching the content.
- When using *num++, you need to enclose (*num), otherwise the system cannot recognize the real meaning you want to express.
- Or you can write *num = *num +1;
code show as below:
#include <stdio.h>
void numplus(int* num)
{
//(*num)++;// 二选一都可
*num = *num + 1;
}
int main()
{
int num = 0;
int i;
for (i = 0; i < 5; i++)
{
numplus(&num);
printf("%d\n", num);
}
}