C-language flexible arrays and dynamic arrays

Source: Internet
Author: User
Tags int size

"Preface" often see two arrays in C language, summarize.

First, a flexible array

Reference: https://www.cnblogs.com/veis/p/7073076.html

#include <stdio.h>typedef struct _softarray{    int len;    int array[];} Softarray;int Main () {    int len = ten;    printf ("The struct ' s size is%d\n", sizeof (Softarray));}


As we can see, the size of the _softarray structure is 4, and it is clear that the next int variable size in the 32-bit operating system is exactly 4, which means that the array in the struct does not occupy memory. Why does it not occupy memory, we usually use an array to explicitly indicate the size of the array? But here it can be compiled to pass it? This is what we often call dynamic arrays, which are flexible arrays.

1. What is a flexible array?

Flexible arrays are arrays of array size, the last element of the struct in C can be an array of unknown size, the so-called 0 length, so we can create flexible arrays with structs.

2. What is the use of flexible arrays?

Its main purpose is to meet the need for variable length of the structure, in order to solve the use of arrays when the memory of the redundancy and array of cross-border problems.

3. Usage :

at the end of a struct, declare a null-length array, which makes the struct variable-length. For the compiler, an array of length 0 does not take up space, because the array name itself does not occupy space, it is just an offset , The name of the array itself represents a non-modifiable address constant (Note: the array name will never be a pointer!) ), but for the size of this array, we can be dynamically allocated, for the compiler, the array name is just a symbol, it does not occupy any space , it in the struct, just represents an offset, represents a non-modifiable address constant!

For This feature of flexible arrays, it is easy to construct structures such as buffers, packets, and so on:

typedef struct _SOFTARRAY


Int Len;

int array[];


Such a variable-length array is often used in network communications to construct an indefinite length of data packets, will not waste space wasted network traffic, such as I want to send 1024 bytes of data, if the fixed length package, false set length of 2048, will waste 1024 bytes of space, will also cause unnecessary traffic waste.

4. Example
#include <stdio.h> #include <malloc.h>typedef struct _softarray{int len;int array[];} Softarray;int Main () {    int len=10,i=0;    The format of the allocated space. At this point the Softarray size is still 4    softarray *p= (softarray*) malloc (sizeof (Softarray) +sizeof (int) *len);    p->len=len;        for (i=0;i<p->len;i++)   {        p->array[i]=i+1;    }    for (i=0;i<p->len;i++)   {          printf ("%d\n", P->array[i]);    }    Free (p);    return 0;}


The purpose of this code is to dynamically create an array with a flexible array and output the contents of the array, and here I will explain the two code directly:

softarray* p = (softarray*) malloc (sizeof (Softarray) + sizeof (int) *10); P->len = 10;

The first sentence is mainly based on the length and data type of the array you want to define and the size of the flexible array itself to open up a piece of memory space to the flexible array p, the second is to define Len's length, and to determine the number of times that the loop printout is a loop.

5. Application of flexible array in "Indeterminate array size"
Arrays are used for arrays with indeterminate len values. If you do not define a flexible array, define the values that the normal array len needs to determine! such as 10,11 ...
#include <stdio.h> #include <malloc.h>
typedef struct _softarray{int len; int array[];} softarray;//print output Fibonacci sequence void Printfln (Softarray *p,int len) {int i; for (i=0;i<len;i++)//loop print output {printf ("%d\n", P->array[i]); }}//dynamically generated Fibonacci sequence void create (int len) {int i; Softarray * p= (softarray*) malloc (sizeof (Softarray) +sizeof (int) *len); Declares struct pointer p, dynamically requests memory, size is struct size + 10 int size//pair indeterminate len value size, using array method. If you do not define a flexible array, define the values that the normal array len needs to determine! such as 10,11 ... for (i=0;i<len;i++)//loop array Assignment {if (I <= 1) {p->array[i] = 1; }else if (I >= 2) {p->array[i] = P->array[i-1] + p->array[i-2]; }else {printf ("Damage:before normal block or after normal block"); Return (-1); }} PRINTFLN (P,len); Free (p);} Main function int main () {int i=0; int Len; printf ("Please enter the number of rows that generate the Fibonacci sequence:");
scanf ("%d", &len); An indeterminate value is passed into the function create (len); return 0;}
Two, dynamic array

Dynamic arrays, which are based on real-time changes, can enlarge the size of the array. The implementation of this function requires pointers and malloc and realloc functions.
int *a = (int*) malloc (10*sizeof (int)); A is equivalent to an array of 10 elements. When the amount of data exceeds 10, use
A = (int*) realloc (A, 20*sizeof (int));//means to increase the size of a to 20, while keeping the original data unchanged.
The above functions include: #include <stdlib.h> #include <malloc.h> or #include<alloc.h>

To illustrate:

#include <stdio.h> #include <stdlib.h>void dimensionalvector () {    int n, i;    int *arr;    Enter a variable value that reflects the relationship between the array and the pointer    scanf ("%d", &n);    arr = (int*) malloc (sizeof (int) *n);    for (i = 0; i < n; i++)        arr[i] = i;    for (i = 0; i < n; i++)        printf ("%d\t", Arr[i]);} int main () {    dimensionalvector ();    return 0;}

It embodies the relationship between array and pointer, and can refer to the transformation relationship between array and pointer.

The difference between three or two people

A flexible array is a structure that uses a pointer-to-array relationship with a dynamic array;

The former, after creation, uses p->array[] to access each value, which directly uses p[] to access each value;


C-language flexible arrays and dynamic arrays

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.