Open Course at Stanford University-Programming Paradigm

Source: Internet
Author: User

Summary
The main content of this lesson is about copying generic data. Although it is implemented in C language and does not use the generic programming technology such as template in C ++, the effect is very good. This section describes the knowledge of byte copy next to the previous section, making full use of the byte Copy technology.
Notes
As the content and examples continue to go deeper, the actual core content is concentrated, so we will only summarize and discuss them here.
Example
All examples in this section are for data exchange, starting from the simplest example and continuing to deepen. Start with an example of the simplest integer data exchange:
Void swap (int a, int B ){
Int tmp =;
A = B;
B = tmp;
}
This example is very simple. You only need to construct a simple intermediate temporary variable tmp to store the value of a and exchange the values related to the value assignment.
However, this instance has a defect, that is, value transfer, rather than reference transfer. In this way, although the passed value is changed, the unit that only wants the original variable has not changed, specifically:
A = 23;
B = 34
Swap (a, B );
When you execute the preceding statement, you will find that the values of a and B are not exchanged because they are related to the value passing and pointer passing of the C/C ++ parameter. When a function is called, only the values of a and B are copied. Therefore, when swap is called, the parameter is exchanged, and the actual parameter value is not changed.
To realize the effect of real parameter passing, we need to use a pointer:
Void swap (int * csv4, int * csv4 ){
Int a = * vp1;
* Vp1. = * VP2;
* Http://dt.ap-southeast-1.maxcompute.aliyun-inc.com/api;
}
When swap (& a, & B) is called again, the original value will be modified because the previous value is passed here, the CIDR operation is an operation directed to units a and B. Therefore, the corresponding value can be modified.
Generic switching and copying
In the above example, only some specific types are exchanged, such as the int type. If you want to exchange the double type, you only need to change its type to double. Other types are similar. But considering the need to exchange a variety of different types, is there a general method? In C ++, the template technology can be used. However, can we recall the byte operations mentioned in the previous lesson by copying bytes? The answer is yes.
Void swap (void * vp1, void * VP2. int size ){
Char buffer [size];
Memcpy (buffer, P0, size );
Memcpy );
Memcpy (KD, buffer, size );
}
When calling, the font size must be set to a certain type. For example, through:
Double a = 23.0, B = 34.0;
Swap (& a, & B, sizeof (double ));
Of course, struct can also be copied in this form.
Some notes about the above example:
1. the array declaration method here. The size and size used are variable, which is only supported by some compilers. Here, we only want to illustrate the character COPY method. The focus of this example is the exchange. Of course, you can use malloc or new to dynamically allocate variable-size space.
2. here we use the memcpy (dest, src, size) function to copy memory units. Note that this function does not care about your data type and simply copies units, therefore, although the compilation may pass, you still need to make judgment and control on your own.
3. The highlight of this example is the use of void *. It can be used to implement generics, that is, for int, short, char, struct, and other types, it can ensure that the copy and exchange are successful.
4. Differences and advantages of template. Note that if a template is used, a code is generated for each type after compilation, such as the one corresponding to the int and the one corresponding to the float. In this way, if the number of calls is large, the code size will increase, excessive redundancy. The code is compiled here, which is more concise.
5. Here we pass a parameter size because the compiler does not know how many bytes to copy because of the existence of the generic pointer void *. Therefore, you need to manually control and specify a size.
Problems
Since the compiler will easily let go of the errors caused by void *, if two different types of data call this function, the problem will occur:
Double a = 23.0;
Int B = 345;
Swap (& a, & B, sizeof (double ));
Here, the size of the data space occupied by the double and int types is different. Therefore, if you call this function directly, an error occurs. The simple result is, truncates or copies multiple data. For example, when the int type is copied to the double data space, only the first two bytes are copied, and the two bytes of the original double data are retained; or when the double type is copied to the int type, an error may occur when two more bytes are copied to the data after the int. The specific method is related to the following parameter sizeof (double) or sizeof (int.
Common Mistakes for beginners
1. use void * tmp = vp1, instead of the char buffer [size] mentioned in the previous lock. This error is caused by the fact that void is not a type and does not belong to a type like int or double, so error. Void can only be used as a function parameter, and the return value is feasible. However, you can use void * tmp = (int) & a, because a specific type can be assigned to a general type. You only need to specify a specific type, in order to let the compiler know the rules before compilation can pass.
2. pointer copying and when to use the reference address. Starting from a simple example,
Char * husband = strdup ("Fred"); char * wife = strdup ("Wilma ");
If you want to exchange the space content pointed to by the two persons, the correct method is:
Swap (& hustband, & wife, sizeof (char *))
That is to say, here we need to exchange the pointer address. After the switch, the content of husb and has changed, and the content has changed to the original content of wife. Because it is the address, the content has changed, in fact, the only address is changed. Now husb and points to the address pointed to by the original wife, while wife points to the address pointed to by the original husb and.
An incorrect example is swap (husband, wife, & sizeof (char *). In this way, what they switch is actually what they lock, that is, the content in the units that store Fred and Wilama will be exchanged, and because char * is four bytes, only four bytes of content will be exchanged. Why? Because the above example, for example, to exchange the content of unit a and unit B, the incoming address is the address of unit a and unit B. Similarly, here I directly pass the pointer, of course, they exchange the content of the unit they direct to, that is, two strings. Therefore, to exchange the content of two pointers, we need to exchange their addresses, that is, the address of the pointer and the pointer of the pointer.
Another example
Consider the following linear search example,
Int * lsearch (int key, int * array, int size ){
For (int I = 0; I <size; I ++)
{
If (array [I] = key)
Return I;
}
}
In the above Code, the subscript of the index is directly returned.
Use bitwise comparison to implement www.2cto.com
Similarly, in order to apply the knowledge we learned above, how can we achieve generic comparison and search? For example, can an int be a struct, a double, or another type. The answer is yes, but we only need to control the compiler and compare the size.
Int * lsearch (void * key, void * base, int size, int elementSize ){
For (int I = 0; I <size; I ++ ){
Void * elemeAddr = (char *) base + I * elementSize;
If (memcmp (key, elemeAddr, elementSize) = 0)
Return elemeAddr;
}
}
Here are several notes: first, the size of the input parameter is the size of the array to be compared. If we do not know the type, we use the void * type, and then we need to input the size of each type, elementSize, which indicates the size of each array member. Because of this, we can precisely locate the specific unit and use the for loop to compare the relationship between each unit and the key. Here, memcmp is used for comparison. The number of bytes for comparison is elementSize, and two pointers are passed in. The comparison pointer is the address of each unit of the array, that is, elemeAddr.

 

Author: deercoder

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.