Reputation: 957
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.
Upvotes: 4
Views: 995
Reputation: 379
struct test {
char name[20];
char position[0];
int x;
int y;
};
0 length arrays are/were quite popular in network protocol code.
Upvotes: 10
Reputation: 145839
Another solution using C11 an anonymous union with an anonymous structure :
struct test {
char name[20];
union {
int position;
struct {
int x;
int y;
};
};
};
The address of position
is the address of the next structure members after name
member.
I show it only for the sake of showing it as the natural solution is to just take the address of member x
in the first structure declaration of your question.
Upvotes: 5