Closed RedsAnDev closed 6 years ago
A simple example about union and blob.
#include <stdio.h>
#include <string.h>
#define WORD_SIZE 256
struct template{
char send_id[6];
char dest_id[6];
char type[3];
char mess[240];
};
union payload{
struct template dataset;
char blob[WORD_SIZE];
};
void printField(char[],int);
int main(){
union payload tmp;
strcpy(tmp.dataset.send_id,"123ABCD");
strcpy(tmp.dataset.dest_id,"456DEF");
strcpy(tmp.dataset.type,"200");
strcpy(tmp.dataset.mess,"Messaggio ricevuto");
printf("\nSTART\n");
printf("SENDER\t\t %s\nRECEIVER\t %s\nTYPE OF MESSAGE\t %s \nMESSAGE\t\t %s \nBLOB\t\t %s\n",tmp.dataset.send_id,tmp.dataset.dest_id,tmp.dataset.type,tmp.dataset.mess,tmp.blob);
printf("\nRemember EOF and %%s\n");
printf("\nSENDER\t\t");
printField(tmp.dataset.send_id,6);
printf("\nRECEIVER\t");
printField(tmp.dataset.dest_id,6);
printf("\nTYPE OF MESSAGE\t");
printField(tmp.dataset.type,3);
printf("\nMESSAGE\t\t");
printField(tmp.dataset.mess,240);
printf("\nEND\n");
return 0;
}
void printField(char elem[],int size){
char tmp[size];
for(int i=0;i<size;i++)
tmp[i]=elem[i];
printf("%s",tmp);
}
Output
START SENDER 123ABC456DEF200Messaggio ricevuto RECEIVER 456DEF200Messaggio ricevuto TYPE OF MESSAGE 200Messaggio ricevuto MESSAGE Messaggio ricevuto BLOB 123ABC456DEF200Messaggio ricevuto
Remember EOF and %s
SENDER 123ABC RECEIVER 456DEF TYPE OF MESSAGE 200DEF MESSAGE Messaggio ricevuto END
Use union as a quickly way to set up structure variable (some net-tool works this way to manipulate package, e.g scapy).
The example you've put is really tricky (especially since valgrind might give you an invalid read).
Use union as a quickly way to set up structure variable Why? Can't you use struct?
Why use a struct within a union? As for a simple example for union I mean something VERY easy, like:
typedef union values {
int int_val;
float float_val;
char char_val;
} values;
int main() {
values union_variable;
union_variable.int_val = 512;
printf("the size of the union is the size of the field having the longest size required: %ld\n", sizeof(union_variable));
printf("the memory for each field is the same. int value is %d but char value is \"%c\" since the first byte of the int value is 0 for amost sure.\n");
}
per spiegare la union