In the process of exchange between the front and back of the game, often used to become the message body, because some content is the size of the location, such as a microblog, the content size of the microblog is unknown.
The general practice is to define a pointer of type char*, and then specify its length, as follows:
typedef struct{unsigned len;char* PData;} MSG;
The use of the time is this:
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 the timing of char* pdata a lot more?
Because the data time is stored in m+1, we can directly get this pointer, without redefining a char* pdata to error this position.
This brings us to another problem where access is inconvenient, we cannot access it in the way of struct members, we can use a flexible array, and see:
typedef struct{unsigned LEN;CHAR data[];} Message;
That's how it's used:
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 divide the complete code comparison:
Array0.h
typedef struct{unsigned len;char* PData;} Msg;typedef struct{unsigned Len;char data[];} Message;
Main.c
Test for 0 size array#include <stdio.h> #include <stdlib.h> #include <string.h> #include "array0.h" int main () {char str[] = "Hello world!"; unsigned len = sizeof (str);//general usage msg* m = (msg*) malloc (sizeof (MSG) +len*sizeof (char)); M->len = Len;m->pdata = (char *) (m+1); memcpy (m+1, str, len);p rintf ("%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);p rintf ("%d,%s\n", Msg->len, Msg->data); free (msg); System ("pause"); return 0;}
C language Variable length message definition: Flexible array