search

Home  >  Q&A  >  body text

c++ - 关于c语言指针的一个简单问题

今天碰到了一个简单的题,可是我却有点不理解,代码是这样的:

#include<iostream>
void inc(char *p)
{
    p = p + 1;
}
int main()
{
    char s[] = { '1', '2', '3' };
    inc(s);
    std::cout << *s << std::endl;
    return 0;
}

需要你判断输出的是什么。
我很确定若想输出‘2’,则inc函数内的代码应该是:

*p=*(p+1);

但是为什么源代码就不能正确run了呢?s本身就是指向数组的第一个元素的指针,我的inc中取的是不是p的地址呢?若是,则为什么不能正确运行?
我感觉这个题目很基础了,可是我却似乎没有学透,请问我下一步要怎么加强对指针的理解呢?
谢谢大家。

黄舟黄舟2773 days ago352

reply all(3)I'll reply

  • PHPz

    PHPz2017-04-17 14:35:07

    First, s is immutable;
    Second, the C language is transfer by value. The s in your inc is a copy of s and has no impact on s;
    Third, are you convinced? The writing does output 2, but you assign s[1] to s[0].

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 14:35:07

    After a slight modification, you know that s is actually an address (pointer), and it points to the first byte, &s[0] == s. Then to change the value inside it, it should eventually be *P = 2; for example, int i =1; when changing this value across functions, you must quote its address, such as int * p = &i, and write *p = 2 like this; here *p==i ; Note that * plus the pointer variable points to the value in this address (pointer). Because changing values ​​across functions usually requires an address to lock the value, and then the value can be changed. So you can change it like this:

    #include<iostream>
        void inc(char *p)
        {
            *p = *p + 1;
        }
        int main()
        {
            char s[] = { '1', '2', '3' };
            inc(s);
            std::cout << *s << std::endl;
            return 0;
        }
        

    Your mistake is that you directly write p = p+1; you are actually trying to change your newly defined pointer variable. You should have learned C++ directly without learning C, or have you not learned C pointers well?

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 14:35:07

    Mobile version + C4Droid code, please forgive me for the confusing layout.


    It can be seen that passing in a pointer can change the object pointed to by the pointer.
    The parameter (here a pointer) passed to the function is a copy. After the function is executed, the copy will be destroyed and the original value will be used.
    Also, you can try using pointers to pointers.

    reply
    0
  • Cancelreply