0 length refers to the definition of an array, specifying its length as 0 (such as int arr[0];), such an array does not occupy the actual space, but can be accessed through the array name to the address it points to. As shown in the following example:
#include <stdlib.h>#include<stdio.h>structdevice{intnum; intcount; intreserve[0]; /** Reserve is an array name, the array has no elements, the address of the array is immediately followed by the structure of the device's *, this method can be cleverly implemented in the C language of the array extension, than the reverse is defined as a pointer, * and to allocate space for the pointer is simpler, And can save a pointer to the storage space*/};intMain () {structDevice * P_dev = (structDevice *)malloc(sizeof(structDevice) +sizeof(int)* -); //sizeof (int) *25 is the specific space of the array reserve (25 elements)P_dev->reserve[0] = -; P_dev->reserve[ -] =0; printf ("p_dev->reserve[0] =%d\n", p_dev->reserve[0]); printf ("p_dev->reserve[24] =%d\n", p_dev->reserve[ -]); printf ("sizeof (struct device) =%d\n",sizeof(structdevice)); //assigns a value of the first content (int value, which is actually reserve[0]) after the structure device to a intA = * (&p_dev->count +1); printf ("A =%d\n", a); return 0;}
Operation Result:
P_DEV->RESERVE[0] = 100
P_DEV->RESERVE[24] = 0
sizeof (struct device) = 8
A = 100
Memory layout:
Num |
Count |
REVERSE[0] |
... |
... |
... |
REVERSE[24] |
|<-------struct Device-------->|
A few points to note:
An array of length 0 does not occupy memory space, and the pointer takes up memory space.
L for a length of 0 array, in the application of memory space, the use of one-time allocation of the principle of the structure of the body containing pointers, the application of space should be separate, release also need to be released separately.
The access to an array of length 0 can be done in an array manner.
Turn from:
Http://blog.chinaunix.net/uid-20196318-id-28810.html
---restore content ends---
The magic of the
0-length array