1

I have a struct like the following

struct Struct {
    int length; //dynamicTest length 
    unsigned int b: 1;
    unsigned int a: 1;
    unsigned int padding: 10;
    int* dynamicTest;
    int flag; 
}

I want to copy this into a char array buffer (to send over a socket). I'm curious how I would do that.

user3701231
  • 45
  • 1
  • 8
  • Your question heading and question body betrays you as someone who may need some [good C++](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) resources. – WhiZTiM Mar 14 '17 at 15:21
  • I feel `unsigned int padding = 10;` probably doesn't do what you think. `char* dynamicTest;` do you want to copy the pointer value? or does it point to some array whose length is greater than 1? ... – WhiZTiM Mar 14 '17 at 15:23
  • I would suggest using serialization say into Json and then send that over network and deserialize on the other end. – Yuriy Ivaskevych Mar 14 '17 at 15:23
  • You're going to have to serialize the object. – NathanOliver Mar 14 '17 at 15:25
  • @WhiZTiM my bad i messed up the unsigned – user3701231 Mar 14 '17 at 15:25
  • @WhiZTiM the value – user3701231 Mar 14 '17 at 15:26
  • If you want to tranfer `dynamicTest` content you must know his size or the end delimiter – Rama Mar 14 '17 at 15:27
  • @NathanOliver, thanks for the answer. Reading resources, it looks like that's the best way. Unfortunately my exercise requires it's sent as a char array – user3701231 Mar 14 '17 at 15:28
  • @Rama, the length of dynamicTest is of length c. – user3701231 Mar 14 '17 at 15:31
  • @user3701231, then you need to reorder struct elements: put the length first and the string last. You could also declare it as `char dynamicTest[1]` and then allocate it dynamically. – Peter K Mar 14 '17 at 15:37

1 Answers1

0

To be precise, you do this with memcpy, e.g.:

#include <string.h>
/* ... */
Struct s = /*... */;
char buf[1024]
memcpy(buf, &s, sizeof(s));
/* now [buf, buf + sizeof(s)) holds the needed data */

Alternatively you can avoid copying at all and view an instance of struct as an array of char (since everything in computer memory is sequence of bytes, this approach works).

Struct s = /* ... */;
const char* buf = (char*)(&s);
/* now [buf, buf + sizeof(s)) holds the needed data */

If you are going to send it over the network, you need to care of byte order, int size and many other details.

Copying bit fields present no problem, but for dynamic fields, such as your char* this naive approach won't work. The more general solution, that works with any other types is serialization.

Peter K
  • 1,787
  • 13
  • 15