对传递给函数的 char 指针使用下标运算符不会修改该值。为什么?
我注意到以下函数:
void myFunction(char *myString)
{
myString[0] = 'H';
}
实际上不会修改 myString。然而,这个函数确实:
void myFunction2 (char *myString)
{
*myString = 'H';
}
对我来说,为什么 myFunction2 有效是显而易见的,尽管我不确定为什么 myFunction 不起作用。你能解释一下吗?
更新: 无需等待。效果很好。我很笨。我可以删除这个东西吗?
I've noticed that the following function:
void myFunction(char *myString)
{
myString[0] = 'H';
}
will not actually modify myString. However, this function does:
void myFunction2 (char *myString)
{
*myString = 'H';
}
It's obvious to me why myFunction2 works, though I'm not sure why myFunction does not work. Could you explain this?
UPDATE:
No wait. It works fine. I'm dumb. Can I delete this thing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,我认为你的说法不对。如果您输入以下代码:
您会发现这两个函数都很好地修改了它们的数据,产生:
所以,如果您实际上看到了您所说的,那么我没有真正的理由怀疑您,除了我的自己丰富的经验:-),问题出在其他地方。
在这种情况下,您需要向我们提供显示错误行为的最小完整程序。
No, I don't think you're right about that one. If you enter the following code:
you'll find that both functions modify their data just fine, producing:
So, if you're actually seeing what you say you're seeing, and I have no real reason to doubt you other than my own vast experience :-), the problem lies elsewhere.
In which case you need to give us the smallest complete program which exhibits the errant behaviour.