Martijn said:
What is the diffrence between the below two notation;
char bytes[1];
char bytes;
But you see the primer as the last member of a structure sometimes,
where this particular member needs to be of a variable size, like so:
typedef struct {
size_t len;
char contents[1];
} rawdata;
Now you can allocate the contents along with the length as one block
and easily address them separately:
rawptr = malloc(sizeof(struct rawdata) + datalength - 1);
I am not able to understand the about datalength how it is going
to achive the "particular member needs to be of a variable size",
and any real time example where we are going to immplement in
above fashion,
Assume that you have 4K of data to store in a structure. It is raw data
which can contain any byte, so you don't have any way of terminating the
stream. So instead of terminating it, you define its length (this is
similar to how Pascal stores strings, BTW). So you could prelude the above
statement with:
datalength = 4 * 1024; /* 4K */
Now 4K + the size of size_t will be allocated in one contiguous block. I am
substracting 1 in the earlier statement because contents already consists of
one byte, so the structure will be one byte too big (see also my note
later). Because C does not do any boundry checking, you can for instance
use
rawptr->contents[4095]
to access the last byte.
But this approach is not recommended. I think a last element of
size 0 is
also done some times, but IIRC this is not portable at all.
As far as i know that you will get teh size od strcut rawdata
to be >5 (In my case it will be 8 bytes, win98, Vc.6)
so how the size is zero ? of the cahr contents[1], it will be one
byte, and for the size of cahr contents; will also be one byte
I have to correct myself on this one, the last element of the array should
be empty, like so:
char contents[];
This is also described in the FAQ:
http://www.eskimo.com/~scs/C-faq/q2.6.html I am not sure, but I think that
last trick is not portable because a compiler might optimize it out in which
case you might miss out on extra space allocated for alignment. But I am
sure others in this NG may be able to be more specific on this matter.
Hope everything's become a bit clearer.
Good luck,