The value assignment between structs of the same type is not necessarily valid.

Source: Internet
Author: User

The value assignment between structs of the same type is not necessarily valid.

The value assignment between structs of the same type is not necessarily valid.

 

Debugging for this issue for a long time today...

 

Previously, I saw a technique about struct usage. This technique can avoid memory fragmentation and ensure that the memory of the struct should not be scattered as much as possible.

Struct struct_name

{

Element_type varible;

...;

Element_type pointer [0];

}

This document describes how to use this function.

 

 

 

For common struct,

 

struct num{int x;int y;};

This type of struct can be assigned operator = Value

 

But!

The special usage described above does not work.

 

#include 
 
  #include 
  
   int main(){struct node{int a;char string[0];};struct num{int x;int y;};struct num m = {1,3};struct num n = {2,4};/***ATTENTION! m = n;*/m = n;printf(m.x:%d m.y:%d n.x:%d n.y:%d,m.x,m.y,n.x,n.y);struct node* p_string_1 = (struct node*)malloc(sizeof(100)+sizeof(int));struct node* p_string_2 = (struct node*)malloc(sizeof(100)+sizeof(int));char hello[] = {Hello world};char panic[] = {Don't panic}; int tmp = 0;for(tmp = 0;tmp < sizeof(hello)/sizeof(hello[0]); tmp++){p_string_1->string[tmp] = hello[tmp];}for(tmp = 0;tmp < sizeof(panic)/sizeof(panic[0]); tmp++){p_string_2->string[tmp] = panic[tmp];}printf(1:%s2:%s,p_string_1->string,p_string_2->string);/***ATTENTION! HERE IS AN EVEIL!*/*p_string_1 = *p_string_2;printf(1:%s2:%s,p_string_1->string,p_string_2->string);free(p_string_1);free(p_string_2);return 0;}
  
 


 


 

Guess what the printed result is?

 

 

 

 

 

 

 

 

 

 

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.