D语言代码打印p为null的原因及修正方法
以下是纠正后的代码:
import std.string : strstr;
import std.stdio;
void main() {
char[] str = 'Hello World, hello world!'.dup;
char* p = strstr(str.ptr,'w'.ptr);
if (p != null) {
printf('%s',p);
}
}
解释:
-
在原代码中,使用了
.dup来复制字符串,但是.dup会返回一个immutable的字符串,无法使用指针修改。因此我们可以直接使用'"w".ptr'来获取'w'的指针。 -
在使用
strstr函数时,如果没有找到匹配的子字符串,会返回null。因此我们需要加上判断,如果p不为null,再打印。
注意:在使用printf函数时,需要包含stdio库。可以在代码的开头加上import std.stdio;。
原文地址: https://www.cveoy.top/t/topic/ofVv 著作权归作者所有。请勿转载和采集!