Detailed explanation of C language pointer Transmission

Source: Internet
Author: User

Passing pointers allows multiple functions to access the objects referenced by pointers without declaring them as globally accessible. To modify data in a function, you must use pointers to transmit data, when the data is a pointer that needs to be modified, it is necessary to pass the pointer. When passing parameters (including pointers), it is passed their values, that is, passed to the function is a copy of the parameter value. This article will discuss the main reason why pointers passed to the function in C language and pointers passed to data from the function returned is that the function can modify data. the following code implements a common exchange function: # include <stdio. h> void swap (int * a, int * B) {int tmp; tmp = * a; * a = * B; * B = tmp;} int main () {int m, n; m = 5; n = 10; printf ("m = % d, n = % d \ n", m, n); swap (& m, & n); printf ("m = % d, n = % d \ n", m, n); return 0 ;} If the parameter is not passed through the pointer, the exchange will not occur. For the specific principle, refer to any C language teaching material to pass the pointer pointing to the constant is a common technology in C, efficiency is very high, because avoid copying a large amount of memory in some cases. If you do not want data to be modified, you need to pass the pointer to the constant. We cannot modify the value passed through the pointer to the constant: # include <stdio. h> void passconstant (const int * num1, int * num2) {* num2 = * num1;} int main () {const int a = 100; int B = 5; printf ("a = % d, B = % d \ n", a, B); passconstant (& a, & B); printf ("a = % d, B = % d \ n ", a, B); return 0;} the following code will produce an error (the second form parameter and the actual parameter type do not match, try to modify the constant referenced by the first parameter): # include <stdio. H> void passconstant (const int * num1, int * num2) {* num1 = 100; * num2 = 200;} int main () {const int limit = 100; passconstant (& limit, & limit); return 0 ;} differences between heap and stack in C Language preparations-the memory allocation of a program is divided into the following parts by the memory occupied by a C-compiled program: 1. stack) -The Compiler automatically assigns release, stores function parameter values, and local variable values. The operation method is similar to the stack in the data structure. 2. heap-generally assigned and released by the programmer. If the programmer does not release the heap, it may be recycled by the OS at the end of the program. Note that it is different from the heap in the data structure. The allocation method is similar to the linked list. 3. Global (static), storage of global and static variables is placed in one area, and initialized global and static variables are in one area, uninitialized global variables and uninitialized static variables are in another adjacent area. The program is released by the system. 4. The text Constant Area-constant string is placed here, and the system releases the program after the program ends. 5. The program code area-stores the binary code of the function body. Next, let's talk about the heap and stack in C language program memory allocation. In general, the program is stored in Rom or Flash when memory allocation is made, and the program needs to be copied to the memory for execution during runtime, the memory stores different information separately, as shown in figure: If the stack area in the memory is in a relatively high address and the address grows in the direction, the stack address increases downward, allocate local variable space in the stack. The heap area increases upwards to allocate the memory space applied by programmers. In addition, static variables and global variables are allocated to static zones. Read-Only zones are allocated with constants and program code spaces, and other partitions. Stack difference, let's look at a classic example: # include <stdio. h> # include <stdlib. h> int a = 0; // The Global initialization zone char * p1; // The Global uninitialized zone int main () {int B; // stack char s [] = "abc"; // stack char * p2; // stack char * p3 = "123456"; // 123456 \ 0 in the constant area, p3 is on the stack. Static int c = 0; // global (static) initialization zone p1 = (char *) malloc (10); // heap p2 = (char *) malloc (10 ); return 0;} I wonder if you have understood it. The first difference between the stack and stack is that the application method is different: the stack (called stack) is automatically allocated space by the system, for example, we define a char a, and the system will automatically open up space for it on the stack. Heap (heap) is the space that programmers apply for as needed, such as malloc (10). Because the space on the stack is automatically allocated and automatically recycled, therefore, the data life cycle on the stack is only released after the function is run and cannot be accessed. The data on the stack can be accessed as long as the programmer does not release space, but the disadvantage is that memory leakage will occur once the programmer forgets to release the data. There are other differences. The summary on the internet is good. Here we will repeat: 1. system Response stack after application: as long as the remaining space of the stack is larger than the requested space, the system will provide the program with memory. Otherwise, an exception will be reported, prompting stack overflow. Heap: First, you should know that the operating system has a linked list that records idle memory addresses. When the system receives a program application, it will traverse the linked list, find the heap node with the first space greater than the requested space, delete the node from the idle node linked list, and allocate the space of the node to the program. In addition, for most systems, the size of the allocation will be recorded at the first address in the memory space, so that the delete statement in the code can correctly release the memory space. In addition, because the size of the heap node is not necessarily equal to the applied size, the system automatically places the excess part in the idle linked list, that is to say, the heap will do some subsequent work after the application, which will lead to the application efficiency problem. 2. Comparison stack of application efficiency: the application is automatically allocated by the system, which is faster. But programmers cannot control it. Heap: Memory allocated by new. It is generally slow and prone to memory fragments. However, it is most convenient to use. 3. Apply for a limited stack size: in Windows, the stack is a data structure extended to the low address and a continuous memory area. This statement indicates that the stack top address and the maximum stack capacity are pre-defined by the system. In WINDOWS, the stack size is 2 MB (OR 1 MB, in short, it is a constant determined during compilation. If the requested space exceeds the remaining space of the stack, overflow will be prompted. Therefore, the space available from the stack is small. Heap: the heap is a data structure extended to the high address and a non-sequential memory area. This is because the system uses the linked list to store the idle memory address, which is naturally discontinuous, And the traversal direction of the linked list is from the low address to the high address. The heap size is limited by the valid virtual memory in the computer system. It can be seen that the space obtained by the heap is flexible and large. 4. stack and stack storage content Stack: when calling a function, the first entry to the stack is the next instruction after the function is called in the main function (the next executable statement of the function call Statement) in most C compilers, parameters are written from right to left into the stack, and then local variables in the function. Note that static variables are not included in the stack. When the function call ends, the local variable first goes out of the stack, then the parameter, and the top pointer of the stack points to the address of the initial storage, that is, the next instruction in the main function, where the program continues to run. Heap: Generally, the heap size is stored in one byte in the heap header. The specific content in the heap is arranged by the programmer. The difference between stack and stack can be illustrated by the metaphor of a senior: using Stack is like eating at a restaurant, just ordering food (sending an application), paying for it, and eating (using it ), when you are full, you don't have to worry about the preparation work, such as cutting and washing dishes, washing dishes, and so on. His advantage is that it is fast, but his degree of freedom is small. Using heap is like making your favorite dishes. It is troublesome, but it suits your taste and has a high degree of freedom. If you do not know how the program stack works, the local variable pointer can easily return an error pointing to the Local Data Pointer. See the following example: # include <stdio. h> # include <stdlib. h> int * allocateArray (int size, int value) {int arr [size]; for (int I = 0; I <size; I ++) {arr [I] = value;} return arr;} int main () {int * vector = allocateArray (5, 45); for (int I = 0; I <5; I ++) {printf ("% d \ n", vector [I]) ;}return 0 ;}once the function returns, the returned array address is invalid, because the function stack frame pops up from the stack, one way is to declare the arr variable as static, so that the variable scope will be inside the function, but allocated outside the stack frame, dodge Replace variable value # include <stdio. h> # include <stdlib. h> int * allocateArray (int size, int value) {static int arr [10]; for (int I = 0; I <size; I ++) {arr [I] = value;} return arr;} int main () {int * vector = allocateArray (5, 45); for (int I = 0; I <5; I ++) {printf ("% d \ n", vector [I]);} return 0;} The following two techniques are often used to return pointers from functions to objects: use malloc to allocate memory within the function and return its address. The caller is responsible for releasing the returned memory and passing an object to the function so that the function can modify it, in this way, allocating and releasing the object memory is the caller's responsibility # include <stdio. h> # I Nclude <stdlib. h> int * allocateArray (int size, int value) {int * arr = (int *) malloc (size * sizeof (int); for (int I = 0; I <size; I ++) {arr [I] = value;} return arr;} int main () {int * vector = allocateArray (5, 45 ); for (int I = 0; I <5; I ++) {printf ("% d \ n", vector [I]);} free (vector ); return 0;} The allocateArray function in the following version passes an array pointer, the length of the array, and the value used to initialize the array element. The returned pointer is only for convenience # include <stdio. h> # include <stdlib. h> int * alloc AteArray (int * arr, int size, int value) {if (arr! = NULL) {for (int I = 0; I <size; I ++) {arr [I] = value ;}} return arr ;} int main () {int * vector = (int *) malloc (5 * sizeof (int); allocateArray (vector, 5, 45); for (int I = 0; I <5; I ++) {printf ("% d \ n", vector [I]);} free (vector); return 0 ;} when a pointer is passed to a function, the value is passed. If you want to modify the original pointer instead of a copy of the pointer, you need to pass the pointer # include <stdio. h> # include <stdlib. h> void allocateArray (int ** arr, int size, int value) {* arr = (int *) mall Oc (size * sizeof (int); if (arr! = NULL) {for (int I = 0; I <size; I ++) {* (* arr + I) = value ;}} int main () {int * vector = NULL; allocateArray (& vector, 5, 45); for (int I = 0; I <5; I ++) {printf ("% d \ n", vector [I]);} free (vector); return 0 ;} binary Tree recursion implementation and double pointer binary tree many operations are often implemented through recursive calls, which determines that the entire process cannot be implemented only through the main function, you also need to call functions defined outside main. Therefore, there are strict requirements for passing the parameters of the function defined outside the main call. I searched for a lot of programs about binary tree creation on the Internet, but I found a lot of errors when I directly copied them on my computer, so I couldn't compile them. The following code compilation does not involve all operations on Binary Trees. The process of creating a binary tree using the C language illustrates problems related to Recursive Implementation and dual pointers. 1. Binary Tree definition the binary tree definition structure is generally in the following form: typedef struct Node {char ch; struct Node * lchild, * rchild;} Node, * BTree; node can generally be used to define Binary Tree nodes, while * B tree can be used to define pointers to Binary Trees (root nodes). 2. The malloc function is required for dynamic memory allocation. It is worth noting that when the function successfully opens up new memory, the void * pointer is returned by default, so it needs to be forcibly converted to the Node * form, its call form is as follows (Node *) malloc (sizeof (Node) 3. recursive calls because of the need for recursive calls, some operations of Binary Trees need to be independently used as a function. However, these functions are called in main, so the processing of passed parameters and returned values is very important. In addition, to operate a binary tree, you must first know the entry of the binary tree, that is, the pointer to the binary tree, that is, the pointer to the root node of the binary tree. Therefore, the passed parameter is a pointer to the root node. The second-level pointer must be passed because of the memory allocation operation. The CreateTree function can be returned or does not return values (because the address is passed ). The test is performed in the main function, and the returned value is the value of the binary tree root node. Void CreateTree (Node ** pTree) {char ch; scanf ("% c", & ch); if (chr = '#') {(* pTree) = NULL;} else {if (! (* PTree) = (Node *) malloc (sizeof (Node) {exit (OVERFLOW) ;}( * pTree)-> ch = chr; createTree (& (* pTree)-> lchild); CreateTree (& (* pTree)-> rchild ));}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.