zoukankan      html  css  js  c++  java
  • C语言柔性数组

    柔性数组:数组大小待定的数组。
    C语言中结构体最后一个元素可以是大小未知的数组。
    C语言可以由结构体产生柔性数组

    柔性数组的结构如何只能堆上生成

    柔性数组是C99的扩展,简而言之就是一个在struct结构里的标识占位符(不占结构struct的空间)。

    #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;
    }

    用柔性数组存储菲波那切数列:

    #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;
    }
  • 相关阅读:
    leetcode 416. Partition Equal Subset Sum
    leetcode 696. Count Binary Substrings
    leetcode 74. Search a 2D Matrix
    leetcode 199. Binary Tree Right Side View
    leetcode 43. Multiply Strings
    leetcode 695. Max Area of Island
    leetcode 257. Binary Tree Paths
    leetcode 694. Number of Distinct Islands
    ros使用时的注意事项&技巧2
    ros使用时的注意事项&技巧
  • 原文地址:https://www.cnblogs.com/siqi/p/4658362.html
Copyright © 2011-2022 走看看