d语言我用以下代码判断char是否在常量区module test_s_trans;import stdstdio;void main immutable char str = Hello world!; 在常量区中声明一个字符串 char ptr1 = castcharstrptr; 将字符串的指针转换为 char char ptr2 = castcharHello worl
您需要将字符串直接声明为 char*,而不是使用 cast(char*) 进行转换。修改代码如下:
module test_s_trans; import std.stdio; void main() { immutable char[] str = "Hello, world!"; // 在常量区中声明一个字符串
immutable char* ptr1 = str.ptr; // 直接声明一个字符串指针
//immutable char* ptr2 = "Hello, world!"; // 直接声明一个字符串指针
assert(ptr1 is immutable); // 判断 ptr1 是否在常量区
//assert(ptr2 is immutable); // 判断 ptr2 是否在常量区
}
这样就可以正确判断字符串是否在常量区了。
原文地址: https://www.cveoy.top/t/topic/fsuy 著作权归作者所有。请勿转载和采集!