当前位置:网站首页>Detailed explanation of zero length array in C language (1) [information at the end of the article]
Detailed explanation of zero length array in C language (1) [information at the end of the article]
2022-07-25 00:51:00 【an520_】
Zero length array concept :
as everyone knows , GNU/GCC In standard C/C++ On this basis, it has made practical expansion , Zero length array (Arrays of Length Zero) Is one of the well-known extensions .
Most of the time , It is used in variable length arrays , Its definition is as follows :

First of all, 0 Length array , Also called flexible array , Make an explanation :
purpose : The length is 0 The main purpose of the array is to meet the need for variable length structures ;
usage : At the end of a structure , Declare a length of 0 Array of , You can make the structure variable in length . For compilers , In this case, the length is 0 The array of does not take up space , Because the array name itself doesn't take up space , It's just an offset , The array name itself represents an immutable address constant
( Be careful : The array name will never be a pointer !), But for the size of this array , We can dynamically allocate .
Be careful : If the structure is through calloc、malloc or person new And other dynamic allocation methods , Free up space when you don't need it .
advantage : Instead of declaring a pointer variable in a structure 、 Then carry out dynamic analysis Matching method , This method is more efficient . Because when accessing the contents of an array , No indirect access is required , Two memory accesses are avoided .
shortcoming : In the structure , The array is 0 Must be declared at the end of , There are certain restrictions on use .
For compilers , The array name is just a symbol , It doesn't take up any space , It's in the structure , It just represents an offset , Represents an immutable address constant !
0 The purpose of the length array :
Let's imagine a scene like this , The data buffer we use in network communication , The buffer contains a len Fields and data Field , Identify the length of the data and the transmitted data respectively , There are several common design ideas :
Fixed length data buffer , Set a sufficient size
MAX_LENGTHData buffer forSet a pointer to the actual data , Every time I use it , Dynamically open up data buffer space according to the length of data
We consider their advantages and disadvantages from the design applied in the actual scene . The main considerations are , Development of buffer space 、 Release and access .
1、 Fixed length bag ( Open up space , Release , visit ):
For example, I want to send 1024 Bytes of data , If you use a fixed length bag , Suppose the length of a fixed length packet MAX_LENGTH by 2048, It will be wasted 1024 Bytes of space , It also causes unnecessary waste of traffic :
Data structure definition :

Data structure size : Consider alignment , So the size of the data structure >= sizeof(int) + sizeof(char) * MAX_LENGTH
Considering the data overflow , In variable length packets data The array length is usually set to be long enough to hold the largest amount of data , therefore max_buffer Medium data In many cases, arrays are not filled with data , So there is waste .
The construction of packets : If we want to send
CURR_LENGTH = 1024Bytes , How do we construct this packet ; Generally speaking , We will return a data structure pointing to the buffermax_bufferThe pointer to :

visit : This memory is divided into two parts ; The first part 4 Bytes
p->len, As a Baotou ( That's the extra part ), This header is used to describe the length of the data section immediately after the header , Here is 1024, So the first four bytes are assigned to 1024 ( Since we are going to construct indefinite length packets , So how long is this bag , therefore , We have to use a variable to indicate the length of the packet , This is it.lenThe role of ); And the memory immediately after that is the real data part , adoptp->data, Last , Carry out amemcpy()Memory copy , Put the data to be sent into this memoryRelease : When the data space is released after use , Just release it

2、 Summary :
Use fixed length arrays , As a data buffer , To avoid buffer overflow , The size of the array is usually set to enough space
MAX_LENGTH, But in actual use , achieveMAX_LENGTHThere's very little data on length , So most of the time , Most of the buffer space is wastedBut the process is simple , It's easy to open up and release data space , No need for programmers to think about extra operations
3、 Pointer packet ( Open up space , Release , visit ):
If you set the length of the top to MAX_LENGTH Replace the fixed length array with a pointer , Dynamic development at each use CURR_LENGTH Size space , Then avoid causing MAX_LENGTH - CURR_LENGTH Waste of space , Only the space of a pointer field is wasted :
Packet definition :

Data structure size : Consider alignment , So the size of the data structure >=
sizeof(int) + sizeof(char *)Space allocation : But it also causes the use of memory allocation , There are two steps

First , You need to allocate a memory space for the structure ; Secondly, allocate memory space for member variables in the structure .
In this way, the memory allocated twice is not continuous , They need to be managed separately . When using arrays of length , The principle of one-time distribution is adopted , Allocate all the required memory to it at one time .
Release : contrary , It's the same when it's released :

Summary :
- Use pointer results as buffers , Only one more pointer size space is used , No need to use MAX_LENGTH An array of lengths , It won't cause a lot of waste of space .
But that's when opening up space , Need to open up extra space for data fields , When casting, you also need to display the space to release the data field , But in actual use , Often open up space in a function , And then back to the user pointing to
struct point_bufferThe pointer to , At this time, we can't assume that users know the details of our development , And release space according to the agreed operation , So it's inconvenient to use , Even cause memory leaks .
4、 Variable length data buffer ( Open up space , Release , visit )
Fixed length array is easy to use , But it's a waste of space , The pointer form uses only one more pointer space , It won't waste a lot of space , But it needs to be allocated many times , Multiple releases , So is there a way to implement it without wasting space , And easy to use ?
GNU C Of 0 Length array , Also called variable length arrays , A flexible array is such an extension . about 0 This feature of long arrays , It's easy to construct into a structure , Such as buffer , Packets and so on :
Data structure definition :

Data structure size : Such variable length arrays are often used to construct indefinite length packets in network communication , Don't waste space, waste network traffic , because char data[0]; It's just an array name , It doesn't take up storage space :
![]()
Open up space : So when we use it , Just open up a space once

Release space : The same goes for freeing up space , Release once

summary :


The length is 0 The array does not occupy memory space , The pointer mode needs to occupy memory space .
For length is 0 Array , When applying for memory space , Adopt the principle of one-time distribution ; For structures that contain pointers , It needs to be done separately when applying for space , It also needs to be released separately .
For length is 0 The array of can be accessed in the form of array
【 Learning exchange group 607439754】
【 Free information package of online disk collected by myself , If you need it, you can collect it yourself 】:
Embedded Internet of things 22 individual STM32 project 、 Competition works ,【 Huaqing vision issued the information package 】
http://makerschool.mikecrm.com/f4wjYBB【 Share some tutorial materials below 】:
Intelligent agricultural sand table
Development of Xiaomi scale technology
Build a smart home project from scratch
Internet of things embedded engineer network foundation
边栏推荐
- 第三章 内核开发
- The number of palindromes in question 9 of C language deduction. Two pointer array traversal method
- Lambda&Stream
- Install and configure php5-7 version under centos7.4
- NXP i.mx6q development board software and hardware are all open source, and the schematic diagram of the core board is provided
- [英雄星球七月集训LeetCode解题日报] 第24日 线段树
- Divide 300000 bonus! Deeperec CTR model performance optimization Tianchi challenge is coming
- torch.nn.SyncBatchNorm.convert_ sync_ Mindspore usage corresponding to batchnorm
- Wireshark packet capturing and rapid packet location skills
- [leetcode weekly replay] 303rd weekly 20220724
猜你喜欢

Advanced multithreading (Part 2)

Unity image control and rawimage

js && ||

如果实现与在线CAD图中的线段实时求交点

Soft test --- fundamentals of programming language (Part 2)
![[Bert] QA, reading comprehension, information retrieval](/img/3b/f632271be813cd71a44b204f5060c4.png)
[Bert] QA, reading comprehension, information retrieval
![[Bert] transformer/bert/attention interview questions and answers](/img/32/5d29ce8056df16211630c3384adcf4.png)
[Bert] transformer/bert/attention interview questions and answers

The font changes with the change of the form
![Why does [mindspore ascend] [custom operator] repeatedly assign values to one tensor affect another tensor?](/img/e3/135ac1e6eade70082c205d16ab8e34.jpg)
Why does [mindspore ascend] [custom operator] repeatedly assign values to one tensor affect another tensor?

Cloud native observability tracking technology in the eyes of Baidu engineers
随机推荐
Digital signal processing synthesis matlab design of dual tone multi frequency dialing system
What are the functions of rank function
[leetcode weekly replay] 303rd weekly 20220724
Why do I have to clean up data?
Uxdb resets the password without knowing the plaintext password
What is the function of transdata operator and whether it can optimize performance
Wireshark introduction and packet capturing principle and process
Does opengauss support using Sqlalchemy connections?
[英雄星球七月集训LeetCode解题日报] 第24日 线段树
paddlepaddle论文系列之Alexnet详解(附源码)
Automated test series selenium three kinds of waiting for detailed explanation
Internal network mapping port to external network
Invitation letter | "people, finance, tax" digital empowerment, vigorously promote retail enterprises to achieve "doubling" of economies of scale
如果实现与在线CAD图中的线段实时求交点
Nodejs package
The model needs to use two losses_ FN, how to operate?
[performance optimization] MySQL common slow query analysis tools
Director of Shanghai Bureau of culture and Tourism: safety is the lifeline of culture and tourism, and we are seizing the new track of yuancosmos
第三章 内核开发
Quartus:17.1版本的Quartus安装Cyclone 10 LP器件库