In the redis source code sds. in h, the string struct is defined as follows: typedefchar * sds; structsdshdr {intlen; intfree; charbuf [] ;}; at the beginning, I didn't understand the form of charbuf, doesn't it mean that the array size in C language must be initialized? So what is it here? We first use a simple method to query
In the redis source code sds. in h, the string struct is defined as follows: typedef char * sds; struct sdshdr {int len; int free; char buf [];}; at the beginning, I didn't understand the form of char buf []. Doesn't it mean that the array size in C language must be initialized? So what is it here? We first use a simple method to query
In the redis source code sds. in h, the string struct is defined as follows: typedef char * sds; struct sdshdr {int len; int free; char buf [];}; at the beginning, I didn't understand the form of char buf []. Doesn't it mean that the array size in C language must be initialized? So what is it here? Let's first use a simple method to check the size of the struct sdshdr: # include Struct sds {int val; int size; char name [] ;}; int main () {printf ("% d \ n", sizeof (sds); return 0 ;} we found that the output result is 8 bytes, that is, char name [] does not occupy space. Here we can regard it as a placeholder. Struct Database
{
Char Name [];
};
This struct declaration is correct, and the latest C standard supports this writing method. However, Initialization is not that simple. No one has mentioned the correct initialization method.
In addition, the initialization of this item can only be manual. First Use malloc (sizeof (struct Database) + size );
The size is the length of the Name you want, and you can only initialize the information found above in strcpy mode. In fact, you can regard char buf [] as a pointer here, by default, struct only occupies pointer space instead of actual storage space. On the contrary, space is allocated only when the struct instance is generated. The space allocation function in redis is in sds. in c: sds sdsnewlen (const void * init, size_t initlen) {struct sdshdr * sh; if (init) {sh = zmalloc (sizeof (struct sdshdr) + initlen + 1);} else {sh = zcalloc (sizeof (struct sdshdr) + initlen + 1);} if (sh = NULL) return NULL; sh-> len = initlen; sh-> free = 0; if (initlen & init) memcpy (sh-> buf, init, initlen ); sh-> buf [initlen] = '\ 0'; return (char *) sh-> buf;} we can see from the above Code that sh = zmalloc (size Of (struct sdshdr) + initlen + 1); this statement applies for memory based on the passed parameters. of course, the applied memory is larger than the space for storing strings, because you need to apply for additional space to store int len; int free; two variables, namely sizeof (struct sdshdr), in which + 1 is used to store '\ 0' indicating the end of the string '.