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


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


    今天为这个问题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;
    }



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


































  • 相关阅读:
    python基础(十七、变量进阶
    python基础(十六、变量进阶
    python基础(十五、变量进阶
    python基础(十四、变量进阶
    python基础(十三、综合应用
    MySQL-索引失效原理
    MySQL-忘记密码
    OSI七层模型
    Python-socket通信
    Python-编程小技巧
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4029770.html
Copyright © 2020-2023  润新知