Why use double indirection? or Why use pointers to pointers?

前端 未结 18 2324
失恋的感觉
失恋的感觉 2020-11-22 10:37

When should a double indirection be used in C? Can anyone explain with a example?

What I know is that a double indirection is a pointer to a pointer. Why would I ne

18条回答
  •  猫巷女王i
    2020-11-22 11:25

    Why double pointers?

    The objective is to change what studentA points to, using a function.

    #include 
    #include 
    
    
    typedef struct Person{
        char * name;
    } Person; 
    
    /**
     * we need a ponter to a pointer, example: &studentA
     */
    void change(Person ** x, Person * y){
        *x = y; // since x is a pointer to a pointer, we access its value: a pointer to a Person struct.
    }
    
    void dontChange(Person * x, Person * y){
        x = y;
    }
    
    int main()
    {
    
        Person * studentA = (Person *)malloc(sizeof(Person));
        studentA->name = "brian";
    
        Person * studentB = (Person *)malloc(sizeof(Person));
        studentB->name = "erich";
    
        /**
         * we could have done the job as simple as this!
         * but we need more work if we want to use a function to do the job!
         */
        // studentA = studentB;
    
        printf("1. studentA = %s (not changed)\n", studentA->name);
    
        dontChange(studentA, studentB);
        printf("2. studentA = %s (not changed)\n", studentA->name);
    
        change(&studentA, studentB);
        printf("3. studentA = %s (changed!)\n", studentA->name);
    
        return 0;
    }
    
    /**
     * OUTPUT:
     * 1. studentA = brian (not changed)
     * 2. studentA = brian (not changed)
     * 3. studentA = erich (changed!)
     */
    

提交回复
热议问题