6.087 Practical Programming in C, lec6

Source: Internet
Author: User
User-defined datatypes, structs, unions, bitfields. Memory allocation. Linked lists, binary trees. Structure

De specified nition: A structure is a collection of related variables (ofpossibly different types) grouped together under a single name.

• Variables can be declared like any other built in data-type.

Struct point ptA;

• Initialization is done by specifying values of every member.

Struct point ptA = {10, 20 };

• Assignment operator copies every member of the structure (becareful with pointers ).

Structure defines a new data type based on existing data types, that is, the element in Struct can also be Struct. The data type specifies the value range of the object in the memory and the operations that can be performed on it. As a result, Struct is not difficult to implement. The memory size is the sum of the sizes of each element in Struct, and the value space is determined by each sub-element in Struct, only a few operators, such as sizeof, can be used. In fact, the size of the memory occupied by Struct is often not simply the size of child elements, because the operating system will align the data for optimization, so that the space occupied by Struct will increase.

Unlike object-oriented class objects, struct assigns values directly instead of passing references. Of course, class objects are also assigned values, because they are references themselves. It is a habit to pass references. The bigger thing is that I have made a mistake. I haven't looked at Java and C ++ for a long time, all are forgotten.

• Individual members can be accessedusing '. 'operator.

Struct point pt = {10, 20}; int x = pt. x; int y = pt. y;

• If structure is nested, multiple '.' are required

Struct rectangle

{

Struct point tl;/upper top left outer/

Struct point br;/your bot right foot/

};

Struct rectangle rect;

Int tlx = rect. tl. x;/nested values/

Int tly = rect. tl. y;

A struct should contain at least the following content: the first address, the size or end address of struct, the type of each member, and the first address of each Member ."." You can think of it as an operator. The name of struct is on the left and the member name is on the right. You can use these two parameters to find the child element. If the result is still struct, you can use it nested ". ", add corresponding child elements to the right.

Structure pointers

• Structures are copied element wise.

• For large structures it is moreef extends cient to pass pointers.

Void Foo (struct Point Comment pp );

Struct point pt;

Foo (& pt );

• Members can be accesses fromstructure pointers using '-> 'operator.

Struct point P = {10, 20 };

Struct point destination pp = & P;

PP −> x = 10;/∗ changes p. x records/

Int y = pp −> y;/define same as Y = P. Y then/

Other ways to access structure members?

Struct point P = {10, 20 };

Struct point destination pp = & P;

(Optional pp). x = 10;/Optional changes p. x records/

Int y = (∗ pp). Y;/∗ same as Y = P. Y then/

Why is the () required?

The answer to the last line is related to the execution sequence, "*" and ". "are all objective operators, and the execution order is from right to left. Therefore, you need to use () to correct the execution order.

Arrays of structures

• Declaring arrays of int: int x [10];

• Declaring arrays of structure: struct point p [10];

• Initializing arrays of int: int x [4] = {0, 20, 10, 2 };

• Initializing arrays of structure:

Struct point p [3] = {0, 1, 10, 20, 30, 12 };

Struct point p [3] = {0, 1}, {10, 20}, {30, 12 }};

I feel that the array definition of struct is no different from the custom type of the system. It should be the same because they are of the same nature.

Size of structures

• The size of a structure is greaterthan or equal to the sum of the sizes of its members.

• Alignment

Struc t {

Char c;

/∗ Padding activities/

Int I;

• Why is this an important issue? Libraries, precompiled indexes les, SIMD instructions.

• Members can be explicitly alignedusing compiler extensions.

_ Attribute _ (aligned (x)/using gcc encoding/

_ Declspec (aligned (X)/descrimsvc samples/

The volume of struct is equal to or greater than the sum of the volume of all its elements, especially in parallel processing. This arrangement makes program design easier. Fortunately, the compiler provides corresponding parameters, this can enable us to force command Data Alignment, thus preventing ambiguity.

Union

A union is a variable that may holdobjects of different types/sizes in the same memory location. Example:

Union data

{

Int idata;

Float fdata;

Char bytes sdata;

} D1, D2, D3;

D1.idata = 10;

D1.fdata = 3.14f;

D1. sdata = "Hello World ";

Union can assume multiple roles at the same time. The difference between Union and struct is a common question in the C language pen interview. Although I think this test is meaningless and boring, I should pay attention to it. Who makes us not strong enough. The Union volume is the same as the largest volume in its element, because it has to put down all types. The implementation of Union should be similar to that of struct. You only need to set the first address of each element to the same one, and reset the memory in each assignment.

Dynamic memory allocation

Void merge malloc (size_t N)

• Malloc () allocates blocks of memory

• Returns apointer to unitialized block of memory on success

• Returns nullon failure.

• The returnedvalue shocould be cast to appropriate type using ().

Int percent ip = (int percent) malloc (sizeof (int) percent 100)

Void merge calloc (size_t n, size_t size)

• Allocates anarray of n elements each of which is 'SIZE' bytes.

• Initializesmemory to 0

Void free (void free)

• Frees memoryallocated my malloc ()

• Common error: accessing memory after calling free

When using malloc, you should note that the memory allocated by malloc is not initialized, that is, there is no clear 0, and calloc initializes the memory to 0. What are the reasons for this difference.

Linked list

De duplicate nition: A dynamic data structure that consists of a sequenceof records where each element contains a link to the next record inthe sequence.

• Linked lists can be singly linked, doubly linked or circular.

For now, we will focus on singlylinked list.

• Every node has a payload and a link to the next node in thelist.

• The start (head) of the list is maintained in a separatevariable.

• End of the list is indicated by NULL (sentinel ).

The appearance of data structures is inseparable from struct, so there is no efficient data structure without struct. The disadvantage of listing is that each listing can only be one type. Object-oriented uses the inheritance structure to solve this problem. A list can store different types (their ancestor classes are the same ), therefore, the object-oriented list and other structures can be called containers.

One of the strongest aspects of the data structure is that their conceptual model is clear, which is equivalent to adding an abstraction. Once upon a time, I was told by a teacher that the data structure determines the algorithm and I never understood it. Are these two mutually reinforcing factors? Now I find that the teacher is very reasonable, because the data structure is dead relative to the algorithm. The one-dimensional model of the Turing Machine determines that the data structure will not have many patterns, but the algorithm is active, the execution sequence of an algorithm can be skipped, and multiple data structures can be used for simultaneous computing. In actual projects, data structures are usually dead and defined in advance. Therefore, algorithms are usually transferred around the data structure.

Binary trees

• A binary tree is a dynamic data structure where each node hasat most two children. A binary search tree is a binary tree withordering among its children.

• Usually, all elements in the left subtree are assumed to be "less" than the root element and all elements in the rightsubtree are assumed to be "greater" than the root element.

Binary Tree is the most streamlined data structure in the tree structure and is easy to use. The tree is also stored linearly in the memory. An important reason for the formation of this tree structure is the existence of recursion. I always feel that recursion is a magic. I remember that all the functions that can be computed on the math machine are recursive functions. Unfortunately, I did not study well and did not understand those mathematical principles.

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.