Sunday, August 21, 2016

Every thing you do I can do it with a double pointer in C

It is 2016, low level coding is not needed anymore. We have programming languages like javascript and python. When people code everything with a class and related methods. But do you remember we have a programming language called C? When we had no class, templates, operator-override or implicit constructor at that time. You actually know what are doing with C, no magic!

I claim no expert to programming, since I only have a four-year-old programming life. But even you are inexperienced like me, you should still be able to code some thing in C. IT IS fatigue to code in C, you have no standard containers to rely on, you spend 10 hours to build a perfect `deque` data type which works on amortized O(1) complexity and has no memory leaks before you are able to work on your project. Awesome!!! But why? Why try to build a huge robust data  structure in a non-OOP language? Instead of trying simulate constructors and destructors, you could always use a double pointer to do the job. Have you ever seen Linus Torvalds's double pointer code? It removes on special case where you would make mistakes. 

But really? what can you do with a double pointer in C? Well, Suppose I have `vector` data structure and I didn't want to write the code like this:
     
     struct vector {
            size_t elem_size;
            void *arr;
     };

we can actually just use a simple array to do the job. If you just pass the `void *` to insert function, how can I modify the size of the vector, or insert anything before header? This should not be a problem with this:

     void insert(void **arr, void *elem, size_t *remain_size, size_t *size) {
        size_t old_size = *size;
         if (*remain_size == 0) {              
                 *arr = realloc(*arr, 2 * *size);
                 *remain_size = *size;
                 *size *= 2;
         }
         *remain_size -= 1;
     //copy the elem to the end
     }

Well, at least you don't want the methods that bad anymore.

No comments:

Post a Comment