如何更改传递给C++中函数的字符串指针的值?
我需要使用功能更改std ::字符串的值。
该函数必须是无效的,并且参数必须是指向字符串的指针,如图所示。
#include <iostream>
void changeToBanana(std::string *s) {
std::string strGet = "banana";
std::string strVal = strGet;
s = &strVal;
}
int main() {
std::cout << "Hello, World!" << std::endl;
std::string strInit = "apple";
std::string* strPtr;
strPtr = &strInit;
changeToBanana(strPtr);
std::cout << *strPtr << std::endl;
return 0;
}
我希望由此产生的印刷品说“香蕉” 其他答案涉及更改参数。
我尝试使用for循环分配字符串,并按元素按元素进行操作,但这无效。值保持不变。
I need to change the value of a std::string using a function.
The function must be void, and the parameter must be a pointer to a string as shown.
#include <iostream>
void changeToBanana(std::string *s) {
std::string strGet = "banana";
std::string strVal = strGet;
s = &strVal;
}
int main() {
std::cout << "Hello, World!" << std::endl;
std::string strInit = "apple";
std::string* strPtr;
strPtr = &strInit;
changeToBanana(strPtr);
std::cout << *strPtr << std::endl;
return 0;
}
I would like the resulting print to say "banana"
Other answers involve changing parameter.
I have tried assigning the string using a for loop, and going element by element, but that did not work. The value remained the same.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于此要求,您无法更改传递给该函数的指针的值,因为它按值传递。
不要将指针与指向的指向混淆。参数按值传递(除非您通过参考将其传递)。进行了副本,并且您对函数中
s
进行的任何更改都不适用于main
中的指针。但是,您可以更改指针指向的字符串(因为
s
指向与main
中的指针相同的字符串):但是,这不是惯用的C ++。您应该传递AA参考
void changetobanana(std :: string&amp; s)
或返回字符串std :: String returnBanana()
。With this requirements you cannot change the value of the pointer that is passed to the function, because it is passed by value.
Don't confuse the pointer with what it points to. Parameters are passed by value (unless you pass them by reference). A copy is made and any changes you make to
s
in the function do not apply to the pointer inmain
.However, you can change the string pointed to by the pointer (because
s
points to the same string as the pointer inmain
):However, this is not idiomatic C++. You should rather pass a a reference
void changeToBanana(std::string& s)
or return the stringstd::string returnBanana()
.s =&amp; strval
将strval
的地址分配给s
。然后,函数结束和对s
进行的任何修改是“忘记”,becases
是 localchangetobanana local 变量>。
因此,调用
changetobanana(&amp; foo)
什么也不做。您要么想要:
要么是这样(因为您不需要指针而选择):
s = &strVal
assigns the address of thestrVal
tos
. Then the function ends and any modifications made tos
are "forgotton", becases
is a local variable ofchangeToBanana
.So calling
changeToBanana(&foo)
does nothing.You either want this:
or this (preferred because you don't need pointers):