Variable length array in C-language struct (flexible array member)

Source: Internet
Author: User

Variable length array in c_struct (flexible array member)

Flexible array member is a feature introduced in the C99 standard of the C programming language (in particular, in sections §6.7.2.1, item, page 103). It is a member of a struct, which was an array without a given dimension, and it must was the last member of such a struct, As in the following example:

struct vectord {    uint8_t  len;    double   // the flexible array member must be last};
    • arr[]Does not occupy the storage space of the structure, sizeof (Strcut Vectord) has a value of 1
    • Variable-length arrays must be the last member of a struct
    • Contiguous storage space adjacent to a struct variable is the arr[] contents of an array
    • A 0-length array is used in GCC arr[0] to represent a variable length array.
struct vectord *allocate_vectord (size_t len) {   struct vectord *vec = malloc(offsetof(structsizeof(vec->arr[0]));   if (!vec) {       perror("malloc vectord failed");       exit(EXIT_FAILURE);   }   vec->len = len;   for0; i < len; i++)       0;   return vec;}

Variable length array in C-language struct (flexible array member)

Related Article

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.