Following article explores the Flexible array member or also called array of length zero. It is very useful when you don't know the size during compile time.
Consider following code
#include <stdio.h> int main() { char a[0]; printf("sizeof a is %d\n", sizeof(a)); return 0; }
sizeof a is 0
Here a is array of size 0, there are no elements in a. a takes no memory at all. You might think there is no use for such a C construct. It is used in very useful one of useful structure called variable length object.
struct buf_tag { int len; char data[0]; };
Here data can be of any length, memory allocated using malloc (dynamic behaviour). Only last member of struct can be flexible array member.
Usage of is explored in below program.
#include <stdio.h> typedef struct buf_tag { int len; char data[0]; }buf_t; int main() { buf_t *a; a = malloc(sizeof(buf_t) + 3); a->len = 3; a->data[0] = 10; a->data[1] = 11; a->data[2] = 12; printf("a len is %d\n", a->len); for(int i = 0; i < a->len; i++) { printf("data[%d] is %d\n", i, a->data[i]); } return 0; }
a len is 3 data[0] is 10 data[1] is 11 data[2] is 12
Above syntax that was used was GNU C standard. C99 dictates that it should be as follows
typedef struct buf_tag { int len; char data[]; }buf_t;
Hence for writing more portable code it is recommended the above way. Make sure allocation matches the len correctly otherwise we could run into issue easily.
Links
- Next Article - C Programming #85: Memory functions
- Previous Article - C Programming #83: designated intializers
- All Article - C Programming
No comments :
Post a Comment