Reputation: 177
struct {
char a[10];
char b[5];
char c[10];
} info;
How can I concatenate all the struct
data members into one single array?
Upvotes: 1
Views: 1624
Reputation: 175
You could use sprintf. This funcions 'prints' a string into anoter:
int struct_size = sizeof(info);
char *result = (char*)malloc(sizeof(char)*struct_size);
sprintf(result, "%s%s%s", info.a, info.b, info.c);
Upvotes: 0
Reputation: 272467
With memcpy()
:
// Assign a buffer big enough to hold everything
char *buf = malloc(sizeof(info.a) + sizeof(info.b) + sizeof(info.c));
// Get a pointer to the beginning of the buffer
char *p = buf;
// Copy sizeof(info.a) bytes of stuff from info.a to p
memcpy(p, info.a, sizeof(info.a));
// Advance p to point immediately after the copy of info.a
p += sizeof(info.a);
// And so on...
memcpy(p, info.b, sizeof(info.b));
p += sizeof(info.b);
memcpy(p, info.c, sizeof(info.c));
Upvotes: 5