How to explain C pointers (declaration vs. unary operators) to a beginner?

前端 未结 23 909
渐次进展
渐次进展 2020-11-30 18:08

I have had the recent pleasure to explain pointers to a C programming beginner and stumbled upon the following difficulty. It might not seem like an issue at all if you alre

23条回答
  •  星月不相逢
    2020-11-30 18:22

    Here you have to use, understand and explain the compiler logic, not the human logic (I know, you are a human, but here you must mimic the computer ...).

    When you write

    int *bar = &foo;
    

    the compiler groups that as

    { int * } bar = &foo;
    

    That is : here is a new variable, its name is bar, its type is pointer to int, and its initial value is &foo.

    And you must add : the = above denotes an initialization not an affectation, whereas in following expressions *bar = 2; it is an affectation

    Edit per comment:

    Beware : in case of multiple declaration the * is only related to the following variable :

    int *bar = &foo, b = 2;
    

    bar is a pointer to int initialized by the address of foo, b is an int initialized to 2, and in

    int *bar=&foo, **p = &bar;
    

    bar in still pointer to int, and p is a pointer to a pointer to an int initialized to the address or bar.

提交回复
热议问题