Home>
# include<stdio.h>
int main (void) {
   char a [] = "012345", * p = a + 1;
    printf ("% d \ n", a);
    (* p) ++;
    printf ("% c \ n", * p);
}


This is a rudimentary question about the C language, but I don't understand why the output is -491984928 and 2.
Please tell me the following questions.
①Do you think a is an array? However, when I displayed it with printf, I didn't know where the numbers came from.
② What is the value in * p, which is 1 in the array in * p = a + 1;
③ I don't understand the meaning of (* p) ++;* p ++;Why does the value change?

c
  • Answer # 1

      

    ①a is the idea of ​​an array?

    Yes.
    However, depending on the context, it may behave as a pointer to the first element.

    # include
    int main (void) {
        int arr [] = {3, 1, 4, 1, 5, 9, 2};
        if (arr ==&arr [0]) {
            printf ("arr ==&arr [0] \ n");// this line is executed
        }
        return 0;
    }

    p = a + 1 is the same as p =&a [0] +1.

      

    But when I display it with printf, I can't figure out where the numbers came from.

    Use the format specifier% s to output a string.

      

    ② * p = a + 1;What value is in * p with 1 added to the array?

    The next address after the start address of the array.
    Also, since char * is a p type, it is p = a + 1 rather than * p = a + 1.

      

    ③ (* p) ++;* p ++;Why does the value change?

    * p ++ is the same as * (p ++).

    Added

    Using a service that visualizes the behavior of code like this makes it a little easier to harden the image.

    If you jump to the link below and wait for a while, the screen will change as shown in the image.
    You can proceed one step at a time with the "Next" button.
    Visualize Python, Java, JavaScript, C, C ++, Ruby code execution

  • Answer # 2

      

    printf ("% d \ n", a);

    displays the address of a (those that do not know where the numbers come from).

    Try changing to

    printf ("% p \ n", a);

  • Answer # 3


    char a [];means an array of char type.
    a [0] is char, a [1] is char, a [] 2 is char ...
    Therefore, ifprintf ("% c", a [0]);is displayed, '0' which is the contents ofa [0]is displayed.
    However,ais not char, but indicates the start address of a [].
    Sincechar a []is declared, the type ofaischar *.
    The start address ofa []is the same as the address&a [0]ofa [0].
    printf ("% d \ n", a);andprintf ("% d \ n",&a [0]);have the same result.


    ais of typechar *, soa + 1is added toaby 1 Byte (one char) Displayed. That is the address ofa [1].