Problem
Read the code of a database syntax parser the other day. In the lexical analysis Syntax Parsing stage, a struct is used to store the types of parsed SQL statements, according to this type, the modified struct is forcibly converted to another struct and assigned to it for further execution. For example, the structure of the data after parsing the storage syntax (Note that there is only one element) is: struct analyze {int type ;}; the different types we agree on represent different SQL operations. If type = 1, it indicates the ALTER TABLE operation, if type = 2, it indicates the Select Operation, and if type is 3, it indicates the CREATE TABLE operation. We have different struct types for different operations to store information, for example, struct alter {int type; int number; char subtype ;............};
Struct select {int type; char relnum; long tablenum ;............}; note that the types of the first element in the structure analyze and alter are the same as those in the SELECT statement. They both represent different operation numbers. Now, if the analyze type is determined to be 1, it is forcibly converted to struct.
Alter and assign the value to the variable of the struct alter type. If the analyze type is determined to be 2, it is forcibly converted to the variable of the struct select type and assigned to the struct select type. Some may ask why the program needs to forcibly convert and assign values to struct of different types?
Problem Analysis
The key to the problem is that when the type in struct analyze stores different values, the corresponding data is stored in the memory next to the struct according to the element type of the struct to be forcibly converted.
For example, when the type in the struct analyze struct is 1, you must follow the struct structure in the high address area next to the struct analyze struct.
Alter data types store the corresponding data, including int and char. When the type in struct analyze is 2
The high address area of analyze stores the corresponding data according to the Data Type of the struct select, including char and long.
In this way, the struct
Analyze and the elements except int type in struct analyze can get the corresponding values.
Simple small example
The following is a simple example to illustrate the forced conversion problem:
struct A{int num;};struct B{int num;char type;int age;};int main(){struct A a;a.num=1;char* tmp1=(char *)(&(a.num));tmp1=tmp1+4;*tmp1='a';int *tmp2=(int *)(&(a.num));tmp2=tmp2+2;*tmp2=100;struct B *b=(struct B *)(&a);printf(" b->num=%d b->type=%c b->age=%d \n",b->num,b->type,b->age);}