zoukankan      html  css  js  c++  java
  • 同类型结构体之间赋值不一定有效

    同类型结构体之间赋值不一定有效


    今天为这个问题debug好久...


    之前看到一个关于结构体使用的技巧, 这个技巧可以避免内存零碎. 保证结构体所属内存尽量不要零散化.

    struct struct_name

    {

    element_type varible;

            ...;

            element_type  pointer[0];

    }

    关于该使用方法的介绍.


    http://blog.csdn.net/cinmyheart/article/details/28985843


    对于普通的结构体,

    	struct num
    	{
    		int x;
    		int y;
    	};

    这样的类型的结构体就能够通过赋值operator =赋值

    可是!

    上面介绍的那种特殊使用方法不行.

    #include <stdio.h>
    #include <stdlib.h>
    
    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;
    }



    猜猜看,打印的结果是什么?


































  • 相关阅读:
    信息爆炸时代,对待信息的三种方式
    Spring事务管理
    归并排序和快速排序的衍生问题
    Linux之Shell命令
    程序员找工作的干货经验
    css3 Transition动画执行时有可能会出现闪烁的bug
    布尔值
    null, undefined理解
    js文字的无缝滚动(上下)
    vue实现文字上下滚动
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4029770.html
Copyright © 2011-2022 走看看