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

前端 未结 23 849
渐次进展
渐次进展 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:14

    int *bar = &foo;
    

    Question 1: What is bar?

    Ans : It is a pointer variable(to type int). A pointer should point to some valid memory location and later should be dereferenced(*bar) using a unary operator * in order to read the value stored in that location.

    Question 2: What is &foo?

    Ans: foo is a variable of type int.which is stored in some valid memory location and that location we get it from the operator & so now what we have is some valid memory location &foo.

    So both put together i.e what the pointer needed was a valid memory location and that is got by &foo so the initialization is good.

    Now pointer bar is pointing to valid memory location and the value stored in it can be got be dereferencing it i.e. *bar

提交回复
热议问题