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

前端 未结 18 2318
失恋的感觉
失恋的感觉 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条回答
  •  清歌不尽
    2020-11-22 11:26

    One thing I use them for constantly is when I have an array of objects and I need to perform lookups (binary search) on them by different fields.
    I keep the original array...

    int num_objects;
    OBJECT *original_array = malloc(sizeof(OBJECT)*num_objects);
    

    Then make an array of sorted pointers to the objects.

    int compare_object_by_name( const void *v1, const void *v2 ) {
      OBJECT *o1 = *(OBJECT **)v1;
      OBJECT *o2 = *(OBJECT **)v2;
      return (strcmp(o1->name, o2->name);
    }
    
    OBJECT **object_ptrs_by_name = malloc(sizeof(OBJECT *)*num_objects);
      int i = 0;
      for( ; i

    You can make as many sorted pointer arrays as you need, then use a binary search on the sorted pointer array to access the object you need by the data you have. The original array of objects can stay unsorted, but each pointer array will be sorted by their specified field.

提交回复
热议问题