0長度數(shù)組是個(gè)奇怪的東西, 下面的代碼(兩種形式之一)是可以通過編譯的. char buf[]; 或者 char buf[0]; 有什么用處呢? 大家知道數(shù)組名其實(shí)是數(shù)組所在內(nèi)存的首地址, 那么0長度數(shù)組的名字,其實(shí)是在內(nèi)存某個(gè)地方中作了一個(gè)標(biāo)記, 在適合的時(shí)候?qū)⑦@個(gè)標(biāo)記后面的一段內(nèi)存作為這個(gè)數(shù)組的內(nèi)容. 貌似數(shù)組下標(biāo)溢出了,但是善于利用這點(diǎn)可以實(shí)現(xiàn)一個(gè)”變長”結(jié)構(gòu)體.
例如下面的代碼:
CODE:#include <stdio.h> #include <stdlib.h> #include <string.h>
static const size_t def_name_len = 32 ; typedef struct __Name { size_t index; size_t len; char buf[0]; } Name, *PName ;
Name * createName(size_t index, const char * strname) { size_t len; PName pname = NULL; if (strname == NULL) { len = def_name_len; } else { len = strlen(strname); } pname = (PName) malloc( sizeof(Name) + len + 1); if(pname == NULL) return NULL;
pname->index = index; pname->len = len; pname->buf[0] = '\0'; |