对传递给函数的 char 指针使用下标运算符不会修改该值。为什么?

发布于 2024-12-10 19:53:01 字数 331 浏览 5 评论 0原文

我注意到以下函数:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

俏︾媚 2024-12-17 19:53:01

不,我认为你的说法不对。如果您输入以下代码:

#include <iostream>

void fn1 (char *s) { *s = 'a'; }
void fn2 (char *s) { s[0] = 'a'; }

int main (void) {
    char str1[] = "hello";
    char str2[] = "goodbye";

    fn1 (str1); std::cout << str1 << std::endl;
    fn2 (str2); std::cout << str2 << std::endl;

    return 0;
}

您会发现这两个函数都很好地修改了它们的数据,产生:

aello
aoodbye

所以,如果您实际上看到了您所说的,那么我没有真正的理由怀疑您,除了我的自己丰富的经验:-),问题出在其他地方。

在这种情况下,您需要向我们提供显示错误行为的最小完整程序。

No, I don't think you're right about that one. If you enter the following code:

#include <iostream>

void fn1 (char *s) { *s = 'a'; }
void fn2 (char *s) { s[0] = 'a'; }

int main (void) {
    char str1[] = "hello";
    char str2[] = "goodbye";

    fn1 (str1); std::cout << str1 << std::endl;
    fn2 (str2); std::cout << str2 << std::endl;

    return 0;
}

you'll find that both functions modify their data just fine, producing:

aello
aoodbye

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文