gpt4 book ai didi

c++ - 在 CPP 中通过指针传递字符串并获得意外输出

转载 作者:太空宇宙 更新时间:2023-11-04 15:17:52 26 4
gpt4 key购买 nike

我试过这段代码,但我不明白为什么我得到的输出是“HL”而不是“Hl”。有人请解释。

void t(string *s){
s[1]='l';
}
int main(){
string s = "HL";
t(&s);
cout<<s;
}

最佳答案

您现在拥有的是通过将不存在的字符串设置为等于 'l' 来更新它。这是未定义的行为。

失败的原因是您在索引指针时就好像它指向一个字符串数组(实际上它指向单个字符串)。您的意思是索引实际的字符串以获取它的字符。您必须首先像这样取消引用指针:

void t(string *s){
(*s)[1]='l';
}
int main(){
string s = "HL";
t(&s);
cout<<s;
}

See live on Coliru

如果您实际上使用了引用,就像您的标题所建议的那样,您不需要在语法方面做任何特殊的事情:

void t(string& s){
s[1]='l';
}
int main(){
string s = "HL";
t(s);
cout<<s;
}

See live on Coliru

关于c++ - 在 CPP 中通过指针传递字符串并获得意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27576349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com