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

前端 未结 4 2738
南笙
南笙 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:15

    When you use the . operator, the compiler translates this to an offset inside the struct, based on the size of the fields (and padding) that precede it.

    For example:

    struct Car {
        char model[52];
        int doors;
        int GasMilage;
    };
    

    Assuming an int is 4 bytes and no padding, the offset of model is 0, the offset of doors is 52, and the offset of GasMilage is 56.

    So if you know the offset of the member, you could get a pointer to it like this:

    int *GasMileagePointer = (int*)((char *)&carInstance + offsetInBytes(GasMile));
    

    The cast to char * is necessary so that pointer arithmetic goes 1 byte at a time instead of 1 sizeof(carInstance) at a time. Then the result needs to be casted to the correct pointer type, in this case int *

提交回复
热议问题