#include <stdlib.h>
struct message
{
int type;
int length;
char data[0];
};
typedef struct message message_t;
message_t *create_message(int type, int length)
{
message_t *temp;
temp = malloc(length + sizeof(message_t));
if (temp != NULL)
{
temp->type = type;
temp->length = length;
}
return temp;
}
int main()
{
message_t *abc;
abc = create_message(10);
return EXIT_SUCCESS;
}
In C, we can declare arrays of objects as follows:
message array[4];
And we're guaranteed that each element is DIRECTLY after the other in
memory, such that we can use a pointer like so:
message *p = &array[0];
++p; //now it points to the 2nd element
++p; //now it points to the 3rd element
++p; //now it points to the 4th element
To facilitate this, the "sizeof" operator returns the full size of the
struct including any necessary padding at the end, such that the next
element in an array can be directly after it.
So, if you define a struct as follows:
struct Monkey { int i; int k; char b; };
It is very probable that it will take up the following amount of memory:
a) 4 bytes for "i"
b) 4 bytes for "k"
b) 1 byte for "b"
c) 3 bytes of padding so the next element can be right after it.
This gives us an overall size of 12 bytes.
Now here's my question:
If we define a structure which has an array at the end of it, how can we be
sure that there's no padding at the end?
-Tomás