Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct labeling

Tags:

c

struct

label

In C I would like to be able to label a specific location within a struct. For example:

struct test {
    char name[20];

    position:
    int x;
    int y;
};

Such that I could do:

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

To copy the position of srs[0] into srs[1].

I have tried declaring position as type without any bytes however this didn't work either:

struct test {
    char name[20];

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

I am aware that I could embed the x and y within another struct 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 was a way to do what I had initially proposed.

like image 779
CHRIS Avatar asked Dec 07 '22 00:12

CHRIS


1 Answers

struct test {
    char name[20];

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

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

like image 58
Nish Avatar answered Dec 31 '22 02:12

Nish