Is the structure address the same as its first element address?

I have Struct as shown below:

struct Bitmask { unsigned char payload_length: 7; unsigned char mask: 1; unsigned char opcode: 4; unsigned char rsv3: 1; unsigned char rsv2: 1; unsigned char rsv1: 1; unsigned char fin: 1; }; const char* payload = "Hello"; const size_t payload_length = strlen(payload); Bitmask* header = new Bitmask(); header->fin =1; header->rsv1 = 0; header->rsv2 = 0; header->rsv3 = 0; header->opcode = 1; header->mask = 0; header->payload_length = payload_length; iovec iov[2]; iov[0].iov_base = (char*)header; iov[0].iov_len = sizeof (header); iov[1].iov_base = (char *)payload; iov[1].iov_len = strlen(payload); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("iov[0].length = %d\niov[1].length = %d\n"), iov[0].iov_len, iov[1].iov_len)); size_t bytes_xfered; client_stream_.sendv_n (iov, 2, 0, &bytes_xfered); cout << "Transfered " << bytes_xfered << " byte(s)" << std::endl; 

I initialize it with the appropriate values. Finally, I want to convert the structure to char * in order to add my payload (this is a char * message) and send it over a network connection.

+6
source share
3 answers

Is the structure address the same as its first element address?

Yes, it is actually provided by the C and C ++ standards. From standard C:

6.7.2.1-13. A pointer to a structure object, appropriately transformed, points to its initial member

The size of your struct should be two bytes. You should not convert the pointer to it to char* : instead, you should use memcpy to copy your Bitmask to the buffer that you send over the network.

EDIT . Since you use I / O with scatter distribution with iovec , you do not need to throw Bitmask at anything: iov_base is void* , so you can just set iov[0].iov_base = header;

Note. This only works as long as your struct does not contain virtual functions, base classes, etc. (thanks Timo).

EDIT2

To get {0x81, 0x05} in your struct , you must reorder the elements of the structure as follows:

 struct Bitmask { unsigned char opcode: 4; unsigned char rsv3: 1; unsigned char rsv2: 1; unsigned char rsv1: 1; unsigned char fin: 1; unsigned char payload_length: 7; unsigned char mask: 1; } 
+14
source

Yes and no.

In general, this is true (as dasblinkenlight explains), but it is not specifically suited for bitfields. Per C ++ 11 9.6 / 3 "no pointers to bit fields", so they also have no addresses. And, obviously, "a pointer to a structure object, appropriately transformed, points to its initial member", breaks if there is no "suitable transformation".

+1
source

The address of the structure is the same as the address of its first member, provided that the corresponding cast is used. Given the declaration of struct my_struct , if item is of type struct

 my_struct, then (char *)item == &item.wp_cval. struct my_struct { char wp_cval; short wp_font; short wp_psize; }ar[ARSIZE]; 
+1
source

Source: https://habr.com/ru/post/908291/


All Articles