zoukankan      html  css  js  c++  java
  • struct和union分析实例

    1.#include <stdio.h>
    #include <malloc.h>

    typedef struct _soft_array
    {
        int len;
        int array[];
    }SoftArray;

    int main()
    {  
        int i = 0;
        SoftArray* sa = (SoftArray*)malloc(sizeof(SoftArray) + sizeof(int) * 10);
        
        sa->len = 10;
        
        for(i=0; i<sa->len; i++)
        {
            sa->array[i] = i + 1;
        }
        
        for(i=0; i<sa->len; i++)
        {
            printf("%d ", sa->array[i]);   
        }
        
        free(sa);
        
        return 0;
    }

    2.#include <stdio.h>
    #include <malloc.h>

    typedef struct _soft_array
    {
        int len;
        int array[];
    }SoftArray;

    SoftArray* create_soft_array(int size)
    {
        SoftArray* ret = NULL;
        
        if( size > 0 )
        {
            ret = (SoftArray*)malloc(sizeof(*ret) + sizeof(*(ret->array)) * size);
            
            ret->len = size;
        }
        
        return ret;
    }

    void fac(SoftArray* sa)
    {
        int i = 0;
        
        if( NULL != sa )
        {
            if( 1 == sa->len )
            {
               sa->array[0] = 1;
            }
            else
            {
                sa->array[0] = 1;
                sa->array[1] = 1;
                
                for(i=2; i<sa->len; i++)
                {
                    sa->array[i] = sa->array[i-1] + sa->array[i-2];
                }
            }
        }
    }

    void delete_soft_array(SoftArray* sa)
    {
        free(sa);
    }

    int main()
    {
        int i = 0;
        SoftArray* sa = create_soft_array(10);
        
        fac(sa);
        
        for(i=0; i<sa->len; i++)
        {
            printf("%d ", sa->array[i]);
        }
        
        delete_soft_array(sa);
        
        return 0;
    }

  • 相关阅读:
    我是5型
    现在的我,有两个状态。我要去找第三个
    什么是BNF范式,什么又是EBNF范式?
    又是好久不写日志
    语料库资源汇总
    原生js与css3结合的电风扇
    JavaScript基础2
    JavaScript基础1
    JavaScript基础4
    JavaScript基础3
  • 原文地址:https://www.cnblogs.com/wxb20/p/6145881.html
Copyright © 2011-2022 走看看