Using "strcpy" to assign value to dynamic char array
Ali Çehreli
acehreli at yahoo.com
Mon Nov 1 21:32:21 UTC 2021
On 11/1/21 2:01 PM, Ali Çehreli wrote:
> The program is as incorrect as its C equivalent would be. ;)
I wrote a cool function to make it easy to disregard memory safety:
import std.stdio;
auto assumedLength(S)(ref S slice) {
struct LengthSetter {
void opAssign(size_t length) {
// Nooo! :)
*cast(size_t*)(&slice) = length;
}
}
return LengthSetter();
}
void main() {
auto arr = [ 1, 2, 3 ];
arr.assumedLength = 10;
writeln(arr);
}
Joking aside, I liked the nested struct and its opAssign to mimic
internal `arr.length = 42` syntax. (I know it involves a potentially
expensive delegate but still...)
Ali
More information about the Digitalmars-d-learn
mailing list