-1

I have these lines:

char sendbuf[BUF_SIZ];
struct ether_header *eh = (struct ether_header *) sendbuf;

I understand that eh will be equal to that struct, but then it equal's again to that struct and has a variable in front of it? If someone can explain to me I would appreciate it.

Yun
  • 3,056
  • 6
  • 9
  • 28
  • 1
    This is casting the address of `sendbuf` to a struct pointer, and then initializing `eh` with that pointer. – Barmar Aug 21 '21 at 15:59
  • `struct ether_header *eh = (struct ether_header *) sendbuf;` is also a [strict aliasing violation](https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule) and undefined behavior. And if `sendbuf` isn't correctly aligned for whatever fields `struct ether_header` has, it'll be undefined behavior for that reason, too. – Andrew Henle Aug 21 '21 at 16:00

2 Answers2

2

It’s assigning the address of sendbuf to eh as though sendbuf were an object of type struct ether_header.

There are two reasons to do this:

  1. In C, you cannot assign a pointer value of one type to a pointer of a different type without an explicit cast, unless one of the pointers has type void *. You cannot assign a char * value to a struct ether_header * object without a cast.
  2. A common (unsafe) practice is to map struct types onto arrays of char or unsigned char by creating a pointer like this. You can set bytes in the array by accessing members of the struct type like
    eh->ether_type = 0x0800;
    . Then you just send the array over a connection using fwrite or something.

It’s unsafe because it’s not guaranteed elements of the struct type will be aligned correctly, and strictly speaking the behavior is undefined.

John Bode
  • 119,563
  • 19
  • 122
  • 198
1

There are two parts of the variable definition:

  1. First the actual variable definition

    struct ether_header *eh
    

    This defines the variable eh as being a pointer to struct ether_header.

  2. The second part is the initialization

    eh = (struct ether_header *) sendbuf
    

    First of all it takes the character array sendbuf and gets a pointer to the first element of the array (sendbuf in this context will decay to &sendbuf[0]), then cast that pointer to pretend it's a pointer to struct ether_header.

    Then it initializes eh to be the same as the pointer on the right-hand side of the =.

Note that the second part isn't assignment, it's initialization.

All of this should be pretty clear if you read any decent beginners book.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621