C语言技巧之长度为0的数组
? ? ?在gnu c中有一種用法,就是可以使用長度為0的數組,比如說一下這個結構體:
struct sample {
int length;
char store[0];
}
可以像以下這種方式來使用:
struct sample * example = (struct sample *)malloc(sizeof(struct sample)+size);
example->length = size;
example->store = example + sizeof(struct sample);
?
這個方法的優勢主要在于你可以在結構體中分配不定長的大小,當然有些人肯定會說,在結構體中不適用這種奇葩的數組,而使用指針不是一樣的么?我們可以比較一下:
?
假設結構體的定義為
struct sample {
int length;
char * store;
}
則使用方式變成
struct sample * example = (struct sample *)malloc(sizeof(struct sample));
example->length = size;
example->store =(char *)malloc(size);
?
而釋放內存時,使用長度0的數組釋放是:
free(example);
而指針方式則
free(example->store);
free(example);
?
從上面的比較可以看書,使用長度為0的數組可以達到更簡單的效果,同時節省了空間,因為使用長度為0的數組對應的結構體的長度為4(0數組不占空間),而指針的結構體對應的長度為8。
轉載于:https://blog.51cto.com/liangqiu/1175742
總結
以上是生活随笔為你收集整理的C语言技巧之长度为0的数组的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Vim案例两则
- 下一篇: 函数式编程学习之路(一)