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

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

    The 2nd statement int *bar = &foo; can be viewed pictorially in memory as,

       bar           foo
      +-----+      +-----+
      |0x100| ---> |  1  |
      +-----+      +-----+ 
       0x200        0x100
    

    Now bar is a pointer of type int containing address & of foo. Using the unary operator * we deference to retrieve the value contained in 'foo' by using the pointer bar.

    EDIT: My approach with beginners is to explain the memory address of a variable i.e

    Memory Address: Every variable has an address associated with it provided by the OS. In int a;, &a is address of variable a.

    Continue explaining basic types of variables in C as,

    Types of variables: Variables can hold values of respective types but not addresses.

    int a = 10; float b = 10.8; char ch = 'c'; `a, b, c` are variables. 
    

    Introducing pointers: As said above variables, for example

     int a = 10; // a contains value 10
     int b; 
     b = &a;      // ERROR
    

    It is possible assigning b = a but not b = &a, since variable b can hold value but not address, Hence we require Pointers.

    Pointer or Pointer variables : If a variable contains an address it is known as a pointer variable. Use * in the declaration to inform that it is a pointer.

    • Pointer can hold address but not value
    • Pointer contains the address of an existing variable.
    • Pointer points to an existing variable
    

提交回复
热议问题