You can declare a pointer to a struct type object.
structmystruct{intA; intb; intc;};structMyStruct SS = { -, -, +};//The struct object SS is declared, and the members of the SS are initialized to 20,30 and 40. structMyStruct *ptr = &ss;//a pointer to the struct object SS is declared. Its type is mystruct *, and the type it points to is mystruct. int*pstr = (int*) &ss;//a pointer to the struct object SS is declared. However, the type of pstr and the type it points to are different from PTR.
How can I access the three member variables of SS through pointer ptr?
Answer:
ptr->a; Point to the operator, or you can (*PTR). A, the former is recommended. Note that here (*PTR) is the SS
ptr->b;
ptr->c;
How can I access the three member variables of SS through pointer pstr?
Answer:
*PSTR;//visited member a of the SS.
* (pstr+1); Member B of the SS was accessed.
* (PSTR+2)//Access member of SS C.
Although I have raised the above code in my msvc++6.0, it is not normal to use PSTR to access struct members, and to illustrate why it is not normal, let's look at how to access the elements of an array by pointers: (replace the struct with an array)
Example 13:
int array[3] = {A,A, A. int *pa = array;
The method by which the pointer PA accesses the array of three cells is:
*PA; Accessed Unit No. 0.
* (pa+1); Accessed unit 1th.
* (pa+2); Accessed Unit 2nd.
The format is the same as the format of the informal method of accessing struct members through pointers.
All the C + + compilers, when arranging cells in an array, always store each array cell in a contiguous storage area, with no gaps between the cells and the cells. However, when you store individual members of a structure object, in a certain compilation environment, you may need to align the words or the two words or something else, and you need to add several "padding bytes" between the adjacent two members, which results in a possible number of bytes of space between the members.
So, in the above example, even if *PSTR accesses the first member variable A of the struct object SS, there is no guarantee that * (PSTR+1) will be able to access struct member B. Because there may be several padding bytes between member A and member B, it is possible that * (PSTR+1) has access to these padding bytes. This also proves the flexibility of the pointer. If your goal is to see if there are any padding bytes between the members of each structure, hey, that's a good idea. However, the correct way for pointers to access struct members should be to use the pointer ptr method in example 12.
Do not hurt the pointer (3)--the relationship between the pointer and the structure type