Detailed Explanation of "C Language Pointer Variables as "Function Parameters"" Review of Computer Science Upgraded Edition (First Draft)

C Language Pointer Variables as "Function Parameters"

In the C language, "function parameters" can be specific data such as "integers, decimals, characters", or "pointers" pointing to them

Using a pointer variable as a function can pass the "address outside the function" to "inside the function", so that the function can operate the data outside the function inside. And these "data" will not be "destroyed" with the end of the function.

Arrays, strings, dynamically allocated memory, etc. are a series of data collections. There is no way to pass all of them into the function through a parameter, only their pointers can be passed, and these data collections can be affected by pointers inside the function.

Sometimes, operations on basic types of data such as integers, decimals, and characters must also use pointers. A typical example is to exchange the values ​​​​of two variables.

// Some beginners may use the following method to exchange the value of two variables:

#include<stdio.h>

void swap(int a,int b)

{

    int kang;//定义一个临时变量kang

    kang = a;

    a = b;

    b = kang;

}



int main()

{

    int a = 65,b=99;

    swap(a,b);

    printf("a=%d,b=%d\n",a,b);

    return 0;

}

result:

a = 66, b = 99

analyze:

It can be seen from the results that the values ​​of a and b have not changed, and the exchange failed.

This is because a, b inside the swap() function and a, b inside the main() function are "different variables" and occupy different memory

They have no connection other than their names.

What swap() changes is the values ​​of their internal a and b, and does not affect the external values ​​of a and b (inside mian()).


 

If you use a pointer variable as a parameter instead, it is easy to solve the above problem

#include<stdio.h>

void swap(int *p1,int *p2)

{

    int kang;

    kang = *p1;

    *p1 = *p2;

    *p2 = kang;

}

int main()

{

    int a = 66, b = 99;

    swap(&a,&b);

    printf("a=%d,b=%d\n",a,b);

    return 0;

}

result:

a = 99, b = 66

analyze:

1. When calling the swap() function, the addresses of variables a and b are "assigned to p1 and p2 respectively". In this way, *p1 and *p2 represent the exchange of the values ​​of variables a and b themselves *p1 and *p2, that is, the exchange of a , the value of b.

2. Although p1 and p2 will be destroyed after the function runs, its impact on the external a and b is "persistent" and will not "restore to its original state" with the end of the function

3. It should be noted that the temporary variable temp, its role is particularly important, because the value of a will be overwritten by the value of b after executing the statement *p1 = *p2; if the value of a is not saved first, it will not be found .


 

This is like taking a bottle of Coke and a bottle of Sprite. If you want to pour Coke into the Sprite bottle and Sprite into the Coke bottle, you must first find a cup, pour one of the two into the cup first, and then pour it into the cup. The cup pours into the bottle. The cup here is a "temporary variable". Although it is only hand-wrapped, it is also indispensable.



 

2. Using arrays as function parameters

An array is a "collection of a series of data", and they cannot be passed "inside a function" at one time through "parameters". If you want to operate an array "inside a function", you must pass an "array pointer".

To put it bluntly, the parameters are passed into the function one by one through the pointer, so there is a for() loop! !

// Let's take a program example below!

#include<stdio.h>

int max(int *kang,int len)

{

    int i,maxValue = kang[0];//假设第0个元素是最大值

    for(i=1;i<len;i++)

    {

        if(maxValue < kang[i])

        {

            maxValue = kang[i];

        }

    }

    return maxValue;

}



int main()

{

    int num[6],i;

    int len = sizeof(num)/sizeof(int);

    //读取用户输入的数据并赋值给数组元素

    for(i=0;i<len;i++)

    {

        scanf("%d",num+i);

    }

    printf("Max value is %d!\n",max(num,len));

    return 0;

}

result:

11 555 999 6 5 888

Max value is 999!

analyze:

The parameter kangkang is just an "array pointer", and the array length cannot be obtained through this pointer inside the function, and the "array length" must be passed into the function as a "function parameter".

Each element of the array num is an integer. When scanf() reads the integer entered by the user, it requires the memory address to store it. num+i means the address of the i-th array element.

When using an array as an argument, the argument can also be given as a "real" array.

//For example, for the max() function above, its parameters can be written in the following form

int max(int kangkang[6],int len)

{

    int i,maxValue = kangkang[0];

    for(i=1;i<len;i++)

    {

        if(maxValue < kangkang[i])

        {

            maxValue = kangkang[i];

        }

    }

    return 0;

}

int kangkang[6] seems to define an array with 6 elements, and when calling max(), all the elements of the array can be passed in at once.

// You can also omit the length of the array, and abbreviate the formal parameters as follows:

int max(int kangkang[],int len)

{

    int i,maxValue = kangkang[0];

    for(i=1;i<len;i++)

    {

        if(maxValue < kangkang[i])

        {

            maxValue = kangkang[i];

        }

    }

    return 0;

}

Although int kangkang[] defines an array, it does not specify the length of the array, as if it can accept an array of any length.

In fact, these two forms of array definitions are illusions, neither int kangkang[6] nor int kangkang[] will create an array, and the compiler will not allocate memory for them, and the actual array does not exist. , they will eventually be converted to pointers like int *kangkang.

This means that both forms cannot pass all the elements of the array in "one brain", and everyone has to use the array pointer properly.

The form of int kangkang[6] only shows that the function expects the array passed by the user to have 6 elements, it does not mean that the array can only have 6 elements, the actual passed array can have less or more than 6 elements.

It should be emphasized that no matter which method is used to pass the array, the length of the array cannot be obtained inside the function, because kangkang is just a pointer, not a real array, so it is necessary to "add an additional parameter" to pass the length of the array. //So there is the parameter int len! ! !


 

Why does the C language not allow all elements of the array to be passed directly, but the array pointer must be passed?

Because the passing of parameters is essentially "the process of assignment", assignment is to copy "memory". The so-called copy refers to copying the data on one piece of memory to another piece of memory.

For basic types of data such as int, float, char, etc., the memory they occupy is often only a few bytes, and memory copying them is very fast. An array is a collection of a series of data. There is no limit to the number of data, which may be few or tens of thousands. It may be a long process to copy them in memory, which will seriously slow down the efficiency of the program. Poor programmers write inefficient code, and the C language does not support direct assignment of data sets syntactically.


 

Guess you like

Origin blog.csdn.net/weixin_51563198/article/details/122784803