把结构定义成一个数组
今天读 freebsd 的源码时发现一个小技巧,经过同事指点,恍然大悟。原来 C 里面还是有好多东西自己不知道的啊。
typedef struct _jmp_buf { int _jb[_JBLEN + 1]; } jmp_buf[1];
这个是 setjmp.h 里的一行定义,把一个 struct 定义成一个数组。这样,在声明 jmp_buf 的时候,可以把数据分配到堆栈上。但是作为参数传递的时候则作为一个指针。这样和 c array 的表现一样了。
btw, 读 freebsd 的源码后,感觉头文件组织比 vc 的强太多了。
Comments
云大不提还没注意到还有这好处。确实相当Nice
Posted by: owent | (16) November 27, 2015 12:00 PM
For standard C code, the number of elements in an array must be positive.
As a GNU C extension, the number of elements can be as small as zero. Zero-length
arrays are useful as the last element of a structure which is really a header for a variablelength
object:
struct line
{
int length;
char contents[0];
};
{
struct line *this_line = (struct line *)
malloc (sizeof (struct line) + this_length);
this_line -> length = this_length;
}
来自GNC C Manual的解释。
Posted by: 涛 | (15) October 17, 2011 10:55 PM
我原来写过一个求职的,在你辞职那个地方...今天百度jmp_buf 第一个就来了这里。。我觉的是缘分。
Posted by: Anonymous | (14) September 18, 2011 08:57 PM
我原来写过一个求职的,在你辞职那个地方...今天百度jmp_buf 第一个就来了这里。。我觉的是缘分。
Posted by: Anonymous | (13) September 18, 2011 08:55 PM
这种技巧只会带来维护的困难,相信编译器的工作吧,你们这些白痴。
Posted by: 云风他爸 | (12) November 21, 2007 12:19 PM
typedef struct sm{ int size; char content[0];};这种用法我觉得主要是想节省内存消耗和字节对其。
这里的content不会分配空间。当写成typedef struct sm{ char size; char content[0];}; 时,这个结构的大小只有1。写成typedef struct sm{ char size; char c1; char c2; char content[0];}; 这个结构的大小是3,而不是对齐后的4字节。
Posted by: gobr | (11) August 26, 2007 04:44 PM
刚好像明白了,一看这个
typedef struct sm{
int size;
char content[0];
} ;
又糊涂了,能不能再解释一下啊?
Posted by: 不空 | (10) December 23, 2005 09:40 AM
还是不太明白,可否请云风讲的清楚一点,谢谢!!
Posted by: Alpha | (9) December 23, 2005 09:31 AM
typedef struct sm{
int size;
char content[0];
} ;
这种在WINDOWS SDK里经常见到,的确常用。
Posted by: madlax | (8) December 22, 2005 09:18 PM
应该说详细点,不然一些同学不大知道,特别对参数传递不大了解的。
_jmp_buf jmp_buf;
如果是这样声明压参数就会把结构中的内容全部压进去
_jmp_buf jmp_buf[1]
这样的话就是压jmp_buf的地址 等同上面那样的用 &jmp_buf 传参
好处在于写着方便
在堆栈使用内存好处是快 只需要移动esp 传参用地址好处也是快 特别对于大结构 并且可以修改原始内容
确实是有不少人用 还有这样一种用法
typedef struct sm{
int size;
char content[0];
} ;
这个也蛮好用,不过会被警告 哈
Posted by: coder | (7) December 22, 2005 12:30 PM
能让写程序方便一点,就已经是很大的用处了。
Posted by: Solstice | (6) December 22, 2005 10:58 AM
这个小技巧只是让写程序方便一点吧......还是想不通有什么特别的大用处
Posted by: 阿立 | (5) December 21, 2005 10:21 AM
多年没写 C 啊,转到 C++ 的时候还没用过这个技法。
这个方法典型的运用就是 jmp_buf,所有 C 编译器都可以认,否则标准的 longjmp 没办法实现。
Posted by: Cloud
| (4)
December 20, 2005 10:30 PM
老大你怎么搞的,写的东西越来越没落了,这不是c的惯用技法吗?
Posted by: dawndu | (3) December 20, 2005 09:58 PM
想了半天也没有明白,这样写有什么好处呢?云风能不能举个使用的例子?
Posted by: ZER0 | (2) December 20, 2005 09:57 PM
加个引用或者->就很麻烦吗?这种语法,主流编译器都能认么?怀疑。
Posted by: Atry | (1) December 20, 2005 05:05 PM