4 ms·
Any special reason why they put the length after the pointer? Or is it just a coincidence?
by hoppelhase 8y ago
Any special reason why they put the length after the pointer? Or is it just a coincidence?
- c-smile 8y agoQuestion is not clear. The Slice is just an address of memory chunk combined with the length of that chunk. That's somehow better than "C strings" - that are just pointers and so you need to do some computation if you need to get length of the string. Such C strings have too many drawbacks - in particular strtok function that modifies input string (that shall be read only all times).
- hoppelhase 8y agoWell, both implementations do have a strict which has the length as last member. Is there any special reason for it? Something like struct-layout optimization?
- zamalek 8y agoYou can re-interpret the struct to a pointer (length would simply be truncated). Apart from that there wouldn't be any benefit: the pointer and length would be aligned no matter which position they take (on x86 and amd64 at the very least).
- c-smile 8y ago"re-interpret the struct to a pointer (length would simply be truncated)." Wrong. It will be pointer-to-pointer. Reinterpretation (to treat struct as a pointer to C string) is only possible if you have something like this: struct BSTR { size_t length; WCHAR chars[N]; // N is length + 1 }; and you return pointer to chars[0]. This is so called Basic string - BSTR is a WCHAR* pointer to memory location prepended by string length field.
- zamalek 8y agoThat's not what I was going after. You can treat the memory location (where the structure resides) as a pointer, plan and simple, nothing more fancy than what I said.
- orra 8y agoI don't think so. My guess would be that it is because a pointer to the struct can be cast to a pointer to T. I /think/ that is defined behaviour.
- int0x80 8y agoIt is: https://port70.net/~nsz/c/c99/n1256.html#6.7.2.1p13 https://port70.net/~nsz/c/c99/n1256.html#6.7.2.1p13