What exactly does the C Structure Dot Operator Do (Lower Level Perspective)?

前端 未结 4 2755
南笙
南笙 2021-02-20 16:42

I have a question regarding structs in C. So when you create a struct, you are essentially defining the framework of a block of memory. Thus when you create an instance of a str

4条回答
  •  囚心锁ツ
    2021-02-20 17:27

    Yes, the dot operator simply applies an offset from the base of the structure, and then accesses the value at that address.

    int x = CarInstance.GasMileage;
    

    is equivalent to:

    int x = *(int *)((char*)&CarInstance + offsetof(Car, GasMileage));
    

    For a member with some other type T, the only difference is that the cast (int *) becomes (T *).

提交回复
热议问题