Forced type conversion can be divided into two situations:
Case 1: When malloc is used to allocate memory
For example:
Test2 *test2 = (Test2 *)malloc(sizeof(Test2));
2. convert a known pointer to a certain type to a pointer of another type.
For example:
Typedef struct test0 {int A; // int C;} test0; typedef struct test1 {test0 * test0;} test1; typedef struct Test2 {test1 test1; // execute the command through int B; int A; // test1 test1; // execution fails} Test2; void main () {Test2 * Test2 = (Test2 *) malloc (sizeof (Test2); test0 test0; test0.a = 111;
// Why is the following statement executed successfully? (Test1 *) Test2)-> test0 = & test0; cout <Test2-> test1.test0-> A <Endl ;}
The above two types of pointer type forced conversion
In the red word, the Test2 pointer variable is forcibly converted from Test2 to test1. why can it succeed?
In fact, this idea itself is wrong"Forcibly convert the Test2 pointer variable from Test2 to test1",
"Forced conversion of pointer type" is actually a wrong idea. There is no forced conversion of pointer type.
In fact, we have not figured out what a pointer is.
The pointer should clarify the four parts: What type is the pointer itself, what type the Pointer Points to, what is the value of the pointer itself, and what is the value of the address to which the Pointer Points?
Case 1:
Test2 * Test2 = (Test2 *) malloc (sizeof (Test2 ));
Here we need to understand that Test2 is a pointer variable of the Test2 * type, while malloc (sizeof (Test2) returns the first address of a void * type memory zone,
So this memory zone should be directed by the pointer of the Test2 type. Then, of course, he must convert a certain region starting with this first address to the Test2 type for the Test2 operation.
Case 2:
(Test1 *) Test2)-> test0 = & test0;
How can this code be executed?
The reason is that Test2 points to the first address of a Test2 type memory zone, while test1 is the first member of Test2, so in fact this first address is actually the first address of test1.
Therefore, Test2 can point the first address of Test2 to a pointer of the test1 type.
To be continued