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

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

    A pointer is just a variable used to store addresses.

    Memory in a computer is made up of bytes (A byte consists of 8 bits) arranged in a sequential manner. Each byte has a number associated with it just like index or subscript in an array, which is called the address of the byte. The address of byte starts from 0 to one less than size of memory. For example, say in a 64MB of RAM, there are 64 * 2^20 = 67108864 bytes . Therefore the address of these bytes will start from 0 to 67108863 .

    Let’s see what happens when you declare a variable.

    int marks;

    As we know an int occupies 4 bytes of data (assuming we are using a 32-bit compiler) , so compiler reserves 4 consecutive bytes from memory to store an integer value. The address of the first byte of the 4 allocated bytes is known as the address of the variable marks . Let’s say that address of 4 consecutive bytes are 5004 , 5005 , 5006 and 5007 then the address of the variable marks will be 5004 .

    Declaring pointer variables

    As already said a pointer is a variable that stores a memory address. Just like any other variables you need to first declare a pointer variable before you can use it. Here is how you can declare a pointer variable.

    Syntax: data_type *pointer_name;

    data_type is the type of the pointer (also known as the base type of the pointer). pointer_name is the name of the variable, which can be any valid C identifier.

    Let’s take some examples:

    int *ip;
    
    float *fp;
    

    int *ip means that ip is a pointer variable capable of pointing to variables of type int . In other words, a pointer variable ip can store the address of variables of type int only . Similarly, the pointer variable fp can only store the address of a variable of type float . The type of variable (also known as base type) ip is a pointer to int and type of fp is a pointer to float . A pointer variable of type pointer to int can be symbolically represented as ( int * ) . Similarly, a pointer variable of type pointer to float can be represented as ( float * )

    After declaring a pointer variable the next step is to assign some valid memory address to it. You should never use a pointer variable without assigning some valid memory address to it, because just after declaration it contains garbage value and it may be pointing to anywhere in the memory. The use of an unassigned pointer may give an unpredictable result. It may even cause the program to crash.

    int *ip, i = 10;
    float *fp, f = 12.2;
    
    ip = &i;
    fp = &f;
    

    Source: thecguru is by far the simplest yet detailed explanation I have ever found.

提交回复
热议问题