Preparing packet to send
Hi everybody! I need your help for a problem. I have to prepare a packet to send. The packet is a char* and it is divided into two parts:
- the first one is a struct made in this way
and its size is 16 bytes (sizeof(data)).
- the second one is a vector (type short int) that contains values and its size depends on data.dim value.
Now I have to concatenate the two strings and I do it in this way:
1) I declare two char* variables
char* buf1 = (char*)data;
char* buf2 = (char*)value;
2) I use char *strcat ( char * dest, const char * src ) function (<string.h>)
char* buffer = strcat(buf1,buf2);
Once that I have transmitted the package, I receive the correct number of bytes but I'm able to extract only the struct values from the buffer. So before sending the package I try to print out the buffer:
and the values (struct data) printed are right.
l = (data*)buffer;
cout << "Data received: " << endl;
cout << "A: " << l->a << endl;
cout << "B: " << l->b << endl;
cout << "C: " << l->c << endl;
cout << "Dim: " << l->dim << endl;
cout << "E: " << l->e << endl;
cout << "F: " << l->f << endl;
cout << "Data_Points: " << l->data_points << endl;
Now I try to print out the values (short int* values):
and the values printed are wrong.
buffer+=sizeof(data); //I move the pointer of sizeof(data) bytes (is it right???)
short int* f;
f = (short int*)buffer;
cout << "Values: " << endl;
for(int j=0; j<(data.data_points); j++)
cout << " Ordinate " << f[j];
Where is the mistake?
p.s.: Sorry for my poor english...
You cannot use strcat to concatenate the two variables into one char* variable because strcat determines the size of the data to copy by finding 0-chars in both strings. It will propably not work as expected. Use memcpy instead.
With memcpy it works fine.
memcpy doesn't allocate memory either. Allocate a new string with malloc, and then copy them both into it.