Cs107-lecture 3-note

Source: Internet
Author: User
Tags arrays mixed

The third lesson continues with memory management, the double, array,struct,&,*, and size end modes are introduced. Jerry will visually visualize memory management operations with a small block diagram. There are many templates in high-level languages, such as binary search, linear search, merge sort, quick sort, etc., when you understand the nature of memory management, you can implement these patterns of memory management yourself. Double

"Whatever bit pattern happened to reside there before are now pretending to being a character for the lifetime of this Stateme NT right here. "
For an expression that enforces type conversions, Jerry always uses this formula to translate the following: "Take address, dereference, force to re-interpret the address, regardless of the variable bit pattern used to be." " e.g.1. Double cast to Char

Double d = 3.1416;
char ch = * (char*) &d; 
Fig. 1. Double cast to Char

E.g.2. is also a forced type conversion, but a double * forces a re-interpretation of &s, which may cause S to crash after having no extra 6 bytes of memory. e.g.2. Short cast to Double

Short s =;
Double d = * (double*) &s;
q&a: Data copy between the size and end machines

A question was raised about the data copy between the large and small end machines. In the case of bit copy, there is no difference, because the byte order of the size end is based on the multi-byte storage, and if it is byte copy, the high-low byte is reversed.

Student: Is these examples gonna behave differently on low NDN?
Jerry: Certainly, yeah. As far as bit copying is concerned, No. This ampersand (&), right here, was always the address of the lowest byte. But as far as how the Ndns have to does more with interpretation and placement of bytes relevant to another. There was these phrase in the handout that I kind of de-emphasized, but they ' re there. struct

Through e.g.3. and FIG. 2 describes the structure in vivo storage operations: e.g.3. Structure in vivo operation

The struct type fraction
struct fraction {
    int num is defined in C + + mode;
    int denom;

Fraction pi;
Pi.num =;
Pi.demon = 7;
((fraction*) &pi.denom)->num = n;
((fraction*) &pi.denom)->denom = 33;
Fig. 2. Structure in vivo storage management

Structs and arrays are introduced in a hybrid, so there is an example of e.g.4 in the form of an array of structures: e.g.4. Managing structures in the form of arrays

The memory of the/*&PI position is considered an array, which is an array of 8byte per element *
/((fraction*) &pi.denom) [0].denom; 

The structure is managed as an array, where the subscript [0] or [1] is actually pointing to a fraction volume, which is the base address for memory access. Array

C + + does not provide array out-of-bounds checking (Bounce Checking), so there are several sets of out-of-bounds examples to demonstrate the side effects of direct manipulation of memory; Java provides a check, but CS107 does not introduce it. e.g.5. Array Access Operation

int array[10];
Array[0] =;
ARRAY[10] = 1;
ARRAY[25] = 25; It's OK
array[-4] =//it ' s OK

E.g.5. Just an example, not a good code, because in C and C + +, when declaring an array, you should pass in the length of the array, the width, and the array that is listed as the element, so that the memory diagram becomes clearer, or the memory management becomes cluttered or even unrecoverable. With Jerry's exact words, I listened many times and it was hard to understand the paragraph:

Jerry: It doesn ' t in C and C + +, not @ all. All it does are instruction for the one declaration as to how many ints to set aside space for. But once-do-like, there's no length of the array is. But the length of the that memory figure, it's not exposed to you. So there ' s no-to-recover it. That's why all you have pass around the length, width, a raw array in C and C + +.

Jerry: You have vectors more than you do raw arrays in C in 106B, but we ' re gonna is more C programmers than C + +.

Jerry highlighted the use of array for memory management in the C language, and the memory management of vectors using C + + STL templates in the 106B course, in a different way. Vectors have advanced memory management features, and arrays deal directly with the underlying. q&a: Why limit array bounds at initialization time.

Student:Say an arrays, like, you initialize it for spaces, but like, what's the point of initializing it's just going to Do, what's basically do-what-want when you inside of it.
Jerry:That's true, actually. This is really just documentation for how much space is being allocated. And then your ' re supposed to write code I ' m not saying the is good code. I ' m just saying its code. Okay? Your ' re supposed to write code that's consistent with the amount of space so you legally has. Just work because there ' s no bounce checking. It doesn ' t look arbitrarily far backwards to figure out whether or not it's an in-range index. If you get away with this, and it compiles, and it runs, it's just gonna put a one where it assumes that the eleventh Entry would be, or the Twenty-sixty entry, or the negative fourth entry. okay?*e.g.6 The syntax of the array memory operation:Array equivalent &array[0] (array+k) equivalent array[k] *array equivalent &array[0] * (array+k) equivalent &array[k] * (array-4) equivalent &array[ -4]

* operation is performed first, so K does not move 4 byte, but 16 byte, enter a rectangle and put a value. Based on the type system, K will know that it is an int * type, starting from the array base address to offset an int length of *k bytes. E.G.7 introduces coercion type conversions for some arrays: forced type conversions for e.g.7 arrays

int arr[5];
Arr[3] = n;
((short*) arr) [6] = 2; 

The forced type conversion of array to short allows it to manipulate arbitrary base units: Fig. 3. Coercion type conversion of array

The output is 512+128, but I verify the output 2 on my computer and it is 2 on paper. This thought is the size of the end problem, and then the younger brother gave the correct explanation. The video is in 2008, when the int or 2 Byte,long int is 4 byte,short (that is, short int) is 1 byte, the course content is also built on 32bit machine, so it is not the problem of machine size end, but the problem of the number of operating system bits. Many C-language classics will emphasize this problem:

Stephen G. Kochan, Programming in C (4th Edition)

"You should never write programs," any assumptions about the size of your data types. You is, however, guaranteed that a minimum amount of storage would be the set aside for each basic type. For example, it's guaranteed that's an integer value would be stored in a minimum of the + bit of storage, which is the size fo A "word" on many computers. "

In addition, the cross-border operation of the array affects the memory to hold the data in the address before and after the array, such as a functional domain function, which is a memory space that is opened up in the stack during the function run phase:

    int A;
    int array[5];
    Double D;

An array's bounds may modify the value of int a or double D, a dangerous model that is also the true pattern of machine work. A mixed model that packages all local variables into an "activity log" (a memory block for all local variables in a function) struct and array

Declares a bytes struct in C + +, with no string in the pure C language, so name is represented as character arrays, at the end of which is a 0 character or null character. e.g. 8. Mixed memory operation of struct and array

struct Student {
    char *name;    Dynamic character array char star
    char suid[8];  Static character array statics character array of length 8
    int numunites; 

Student Pupils[4];
Pupils[0].numunits = +;
Pupils[2].name = StrDup ("Adam");
strcpy (Pupils[1].suid, "2014110xxx");

An evaluation pointer expression, 6 is a pointer-plus-decrement operation based on the char* type
pupils[3].name= pupils[0].suid + 6; 
strcpy (Pupils[3].name, "123456");

where Strdup=shorthand for string duplicate,dynamically allocates just enough space to store the string,strdup does not specify an address, but instead allocates a Write ' Adam ' in Block memory and return ' Adam ' address, strcpy does not assign an address, but internally specifies a piece of address. There is a for loop in strcpy that character copy one after another until 0 (0 is also copy). StrDup seems to be the later malloc. Q&a: How the structure is stored in memory.

Jerry:"in 106B and 106X, and maybe 106A as well, you drew them as the somewhat loose rectangels around. Okay, I want to is a little bit more structured than that. I want to recognize so the amount of memory that's set aside for the struct fraction, not surprisingly, is eight bytes. Okay? It ' s obviously the sum of some of its parts, and it actually packs all of those bytes as tightly as possible. "

The storage of the structure in memory requires consideration of the order of the variables in the memory address, as well as the case of byte alignment among the various variables. Fig. Is the diagram of the structure's storage in memory:

in e.g. 8, line 13 evaluates the pointer expression, strcpy will treat Pupils[0].suid+6 as a series of character sequence space base address, passed to Pupils[3].name, at this time pupils[3]. The name should be saved as 0x1000,0x1001 ... Such an address value. After obtaining the base site, one after the base address, assign a value to the small box, or print out the characters. Fig. 5. Memory Diagram

"Generics" in the C language

The generic nature of the C language is a simple function plus advanced memory terminology, such as the most common swap functions:

void swap (int *ap, int *bp);
    int temp = *AP;
    *ap = *BP; Evaluates the portion of the *BP that it addresses
    = *temp;
int x = 7;
int y = 117;
Swap (&x, &y)

In fact, this kind of exchange process and int independent, can be double,char,struct,student ... Although it is not necessary to write generics in C, this is really a way, especially if you understand the principle of memory. The next lesson introduces this type of generics, with a generic pointer and a generic byte exchange to form a new understanding (in terms of generic pointers and generic byte).

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.