You have to know the pointer base-6. Initialization of memory and use of structure

Source: Internet
Author: User

One, memory use 1.1 The memory area you created may be dirty

When we create an area of memory, the data in memory can be messy (possibly the data left behind by other code), such as the following code:

int Main (intChar *argv[]) {    // the 20 bytes of memory requested below may have been used by someone else    Char chs[];     // This code may be garbled, because the%s of printf is "printing has been encountered '".     printf ("%s\n", CHS);     return 0 ;}

Its run result is as shown in garbled, because printf's%s is " printing has been encountered '".

1.2 Ways to resolve dirty memory areas

So, how do we solve the dirty memory areas we might be accessing above? In the C language, there are two ways to do this:

(1) Use the Memset function to first clean up the memory:

void *memset (void *s, int ch, unsigned n);

Sets the contents of each byte in a piece of memory pointed by S to the ASCII value specified by CH,

The size of the block is specified by the third parameter, which usually initializes the newly requested memory.

its return value is a pointer to S.

Then we can use the Memset function to clean up the memory, which is populated with the area of memory created:

intMainintargcChar*argv[]) {    //the 20 bytes of memory requested below may have been used by someone else .    Charchs[ -]; //This code may be garbled, because the%s of printf is "printing has been encountered '". printf"%s\n", CHS); //memset Memory initialization: memset (void *, data to be populated, number of bytes to populate)memset (CHS,0,sizeof(CHS)); inti,len=sizeof(CHS)/sizeof(Char);  for(i=0; i<len;i++) {printf ("%d |", Chs[i]); }    return 0;}

You can see that the code runs as shown, with 20 bytes set to 0.

Typically, the Memset function is used to clean up the area of memory that is created in the heap space.

(2) Fill 0 with initialization:

In addition to using the Memset function, another straightforward way is to specify the data to be populated directly at initialization, as in the following code:

intMainintargcChar*argv[]) {    inti; Charchs[ -] = {0 };  for(i=0;i<sizeof(CHS)/sizeof(Char); i++) {printf ("%d |", Chs[i]); } printf ("\ n"); intnums[Ten] = {7,5 };  for(i=0;i<sizeof(nums)/sizeof(int); i++) {printf ("%d |", Nums[i]); }    return 0;}

You can see the result of the run: for an int array, if you do not initialize it, the 0 to memory area is populated by default.

II. structure Use 2.1 Initialization of the structure body

A struct is actually a chunk of memory that we can format to store and read. As the following code shows, we try to define a struct:

 struct   _person{ char  *name;     int  age; double  height;  int  Main (int  argc, char  *argv[]) { struct   _person P1;  //  uninitialized memory area is dirty  printf ( " p1.age is%d\n  "  ,p1.age);  return  0  ;}  

In the main function, we declare a struct P1 that has just been defined, but we do not initialize it. At this point, the problem with the dirty memory area mentioned above appears as follows:

How to solve it, or use the two methods described above:

(1) Memset:

    //method One: Use memset for cleanupmemset (&AMP;P1,0,sizeof(struct_person)); printf ("P1.age is%d\n", P1.age); P1.name="Zhou Xurong"; P1.age= -; printf ("Name:%s, age:%d\n", P1.name,p1.age); printf ("P1.age is%d\n", P1.age); printf ("------------------------------\ n");

Note that the third parameter here is sizeof (struct _person)

(2) initialized to 0:

    // method Two: Initialize    struct 0  };     " Andy Lau " ;      - ;    printf ("Name:%s, Age:%d\n", p2.name,p2.age);

The two pieces of code run as shown in the results:

The first line is the dirty memory data that is not cleaned, the second part is the result of using memset to clean and then assign the value, the third part is the result of the direct initialization and then the assignment.

2.2 Structure body size with pointers

For structs of ordinary data types, it is easy to calculate the size of the structure body. But what if there is a struct with pointers? I think a lot of rookie like me will make mistakes. So, let's see what the size of that structure is, right?

struct_person{Char*name;//pointer is 4 bytes, address (int)    intAge//4 bytes    DoubleHeight//8 bytes};intMainintargcChar*argv[]) {    struct_person p1; printf ("The size of P1 is%d\n",sizeof(struct_person)); return 0;}

The size of the structure is calculated as 16 by the sizeof function! Yes, you're not mistaken! Not 13, but 16.

So, the question is, why is it 16? Originally, for int, short and so on to the structure of the storage is occupied by the corresponding byte, but for char*, etc., it is just the pointer (address) to save it. The so-called address, is a number, then here is an integer number representing the memory address, so it accounts for 4 bytes, 4+4+8=16.

So, the question comes again, what if I assign a long, long string to name in the main function?

struct 0  " Andy Lau Andy Lau Andy Lau Andy Lau Andy Lau Andy Lau Andy Lau Andy Lau ";

We again calculate the size by sizeof, which is still 16! Why, we can take a look at the following picture:

As you can see, no matter how long a string we assign to name, it is always stored as a pointer to a specific string, an address (a magical number), and the size of the struct does not change depending on the size of the string that points to it.

2.3 using typedef to alias struct bodies

In the preceding code, we declare struct _person every time we use a struct, such as:

struct _person p1={0}; sizeof (struct

This is more troublesome, you can use a typedef to take an alias:

typedefstruct_person{Char*name;//pointer is 4 bytes, address (int)    intAge//4 bytes    DoubleHeight//8 bytes} person;intMainintargcChar*argv[]) {Person P= {0 }; P.name="Edison Chen"; P.age= the; printf ("Name:%s, age:%d\n", P.name,p.age); return 0;}

Look, isn't it much more refreshing?

Three, the structure of the copy assignment problem 3.1 The structure of the duplication is actually "deep copy"

In C language, the duplication of a struct is actually a copy of the whole rather than a copy of the address, as in. The concept of deep copy in net is similar (deep copy and shallow copy is a more important concept in. net). For example, the following section of code:

Person P1 = {0 }; P1.name="Edison Chen"; P1.age= the; //The following copy actually copies a copy of theperson P2 =P1; P1.age= -; printf ("P1. Name:%s, p1. Age:%d\n", P1.name,p1.age); printf ("P2. Name:%s, p2. Age:%d\n", P2.name,p2.age); printf ("Address:%d,%d\n", &AMP;P1,&AMP;P2);

As you can see from the results below, even though we changed the age of the original P1 after the copy, P2 's age is still the value before the change. Finally, from the memory address of the two structures, it can be seen that two structures are separate memory spaces (two addresses are 16 bytes apart, just the size of the struct).

3.2 How to implement a "shallow copy" of a struct

If we want to refer to a struct multiple times in a program, rather than want to copy a new copy every time, this increases memory usage, which is where we are. NET is often referred to as a shallow copy (copy only the reference address). Then, we can use a pointer to the struct body to implement.

    person* p3 = &p1;      - ;    printf ("p1. Name:%s, p1. Age:%d\n", p1.name,p1.age);    printf ("p3. Name:%s, p3. Age:%d\n", p3->name,p3->age);     // for struct pointers, take members to use, instead of.    printf ("Address:%d,%d\n", &P1,P3);

It is important to note that, for struct pointers, the fetch member is to be used, instead of.

Let's look at the results of the operation and find that two addresses are the same memory address used:

Resources

such as Peng Network, "C language can also do big Things (third edition)"

Zhou Xurong

Source: http://edisonchou.cnblogs.com

The copyright of this article is owned by the author and the blog Park, welcome reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to give the original link.

You have to know the pointer base-6. Initialization of memory and use of structure

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.