Variable-length message definition in C language: flexible array
In the process of game front-end exchange, the message body is often used, because the size of some content is the location, such as a microblog, and the size of Weibo content is unknown.
The general practice is to define a char * type pointer and specify its length. The Code is as follows:
typedef struct{unsigned len;char* pData;}Msg;
The usage is as follows:
char str[] = "hello world!";unsigned len = sizeof(str);Msg* m = (Msg*)malloc(sizeof(Msg)+len*sizeof(char));m->len = len;m->pData = (char*)(m+1);memcpy(m+1, str, len);printf("%d, %s\n", m->len, m->pData);
Do you think there is a lot of char * pData at the time?
Because the data storage location is m + 1, we can get this pointer directly without the need to redefine a char * pData to report this location.
This leads to another problem: Access is inconvenient. We cannot access it by using struct members. You can use flexible arrays and see:
typedef struct{unsigned len;char data[];}Message;
The usage is as follows:
Message* msg = (Message*)malloc(sizeof(Message) + len*sizeof(char));msg->len = len;memcpy(msg->data, str, len);printf("%d, %s\n", msg->len, msg->data);free(msg);
To compare the complete code:
// Array0.h
typedef struct{unsigned len;char* pData;}Msg;typedef struct{unsigned len;char data[];}Message;
// Main. c
// Test for 0 size array # include
# Include
# Include
# Include "array0.h" int main () {char str [] = "hello world! "; Unsigned len = sizeof (str); // common usage Msg * m = (Msg *) malloc (sizeof (Msg) + len * sizeof (char )); m-> len = len; m-> pData = (char *) (m + 1); memcpy (m + 1, str, len); printf ("% d, % s \ n ", m-> len, m-> pData); free (m); // flexible array Message * msg = (Message *) malloc (sizeof (Message) + len * sizeof (char); msg-> len = len; memcpy (msg-> data, str, len); printf ("% d, % s \ n ", msg-> len, msg-> data); free (msg); system ("pause"); return 0 ;}