Structural marking

In C, I would like to be able to mark a specific location within a structure. For instance:

struct test {
    char name[20];

    position:
    int x;
    int y;
};

What could I do:

struct test srs[2];
memcpy(&srs[1].position, &srs[0].position, sizeof(test) - offsetof(test, position));

Copy the position of srs [0] to srs [1].

I tried to declare the position as a type without any bytes, however this did not work either:

struct test {
    char name[20];

    void position; //unsigned position: 0; doesn't work either
    int x;
    int y;
};

I know that I could embed x and y in another structure called position:

struct test {
    char name[20];

    struct {
        int x;
        int y;
    } position;
};

Or just use the location of the x property:

struct test srs[2];
memcpy(&srs[1].x, &srs[0].x, sizeof(test) - offsetof(test, x));

However, I was wondering if there is a way to do what I originally proposed.

+4
source share
2 answers
struct test {
    char name[20];

    char position[0];
    int x;
    int y;
};

0 arrays of length / were quite popular in the network protocol code.

+8
source

Another solution using C11 anonymous union with anonymous structure:

struct test {
    char name[20];

    union {
        int position;
        struct {
            int x;
            int y;
        };
    };
};

position - name.

, - x .

+4

All Articles