Typedef, Structs, Reusability without OO

This is a discussion on Typedef, Structs, Reusability without OO within the C Programming forums, part of the General Programming Boards category; I know C is not an OO language, but I'm modelling my code of those concepts and I want to ...

  1. #1
    Registered User
    Join Date
    Dec 2009
    Posts
    47

    Typedef, Structs, Reusability without OO

    I know C is not an OO language, but I'm modelling my code of those concepts and I want to essentially make multiple "struct instances", here's my goals:

    1) Create a struct with a dynamic array
    2) Use multiple instances of the struct, all seperate and unique
    3) less code, more reusability

    Code:
    typedef enum
    {
        false,
        true,
    
    }bool;
    
    typedef struct table
    {
    
            int *array = NULL;
            int *count = 0; 
            int *size;
    
            bool new( int length, int fill )
            {
                    int i;
    
                    *size = length;                         
                    *count = (length*fill);
                    array = (int*)malloc(length * sizeof (int)); /*Allocate memroy*/
    
                    if (array == NULL) 
                    {
                            printf("ERROR! Could not allocate memory for array\n");
                            return false; /*Memory allocation failure*/
                    }
    
                    for(i=0;i<length;i++)
                            array[i] = fill;
    
                    return true; 
            }
    
            /*Destructor - Free allocated memory and set pointer to null*/
            int delete()
            {
                    free(array);
                    array = NULL;
            }
    
    }table;
    
    int main()
    {
      //not sure how to go about this....
    }
    So basically I want this "table" variable I can create many instances of (each unique and seperate). Then I want to add more inline functions and variables. I am not sure if the above is correct or how I would go about it in C.

    I was thinking, I would have to allocate memory for each instance of a "table" variable, but since the array within it is dynamic the memory I allocate for the "table" variable might not be enough....so I may have to reallocate memory.

    Any ideas, or tips on how to proceed would be great and I would really appreciate it. First attempt at C!

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,163
    You can't define methods in a C struct.
    If you understand what you're doing, you're not learning anything.

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    An OO approach in C is not tied to class nomenclature, etc. It's pretty straightforward, just simple logic.

    If you have worked with linked lists before, think about the methodology there: you have a bunch of functions that act on objects. The methods are external to the object in the code, however.

    So, you want a new_table function:
    Code:
    table *new_table (int len, int fill);
    You can stick those in an array, eg, by calling it from another function that works with the array as it's own class (separate from table) -- that maybe another struct, or it could just be:
    Code:
    int addToTableArray (table **array, int len, int fill);   /* calls new_table() internally */
    I prefer int as a return value to bool. There is no real purpose or advantage to using bool, just return 1 or 0. You can always expand the meaning of an int later, whereas with a bool you cannot.

    Like I said, it's all just common sense. This is where OO came from. Having knowledge and experience with a language that actually uses "classes" and "objects" will probably provide you with insights and ideas with C, just don't get too hung up on duplicating it too stringently -- there is no advantage to that. OO is a convenience for programmers, do not regard it as something with some sort of higher metaphysical value (eg, as if making it work exactly that way will improve the performance of the program -- no, it won't). In fact, keeping your code and thoughts organized without strictly defined classes and objects is more likely to lead to improved performance. Class structures often represent an unnecessary overhead, esp. if you force your code to fit the paradigm. Apply the OO perspective where it seems natural, but don't make it a goal unto itself, and don't tie your hands with rules and regulations that do not exist in C.

    I have seen people recommend using function pointers inside structs to duplicate methods. Generally, this is a bad idea and is exactly what I meant by "forcing your code to fit a paradigm".
    Last edited by MK27; 12-04-2009 at 09:51 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Making the structs you want is not a big deal, but trying to make your C program like an OO program, is unwise, imo.

    If you make your functions robust, there's no reason they can't be reused. I believe the C standard library has many excellent examples of that.

    I would suggest focusing on what you want your program to do, and then working out a good top-down design for it.

    Hiking in the Sahara Desert is entirely different from hiking in the high Andes mtns. Trying to make them the same will undoubtedly be difficult, and prone to failure.

    As you make each struct dynamically, you also malloc (or calloc), the memory for the dynamic array in each struct. Nothing needs to be reallocated.

  5. #5
    Registered User
    Join Date
    Dec 2009
    Posts
    47

    Ok, rework. More insight please! thanks guys

    Thanks for all the insight, i'm still not sure if I can accomplish what I want by but here's some code. Basically, two seperate table variables, im not sure if I set it up right or if im modifieing variables accordingly.

    Code:
    int main()
    {
    
            table *t1;
            table *t2;
    
            t1 = new(4, 1);
            t2 = new(2, 3);
    
            delete( t1 );
            delete( t2 );
    
    typedef struct table
    {
            /*Innitialize all values incase we use accidentally*/
            int *array = NULL; /*Default for pointers (points to nothing)*/
            int count = 0;    /*Default for counter (empty array)*/
            int size;
    };
    
    
    /*Constructor - Innitialize variables and dynamically create integer array*/
    table *new( int length, int fill )
    {
            int i;
            table mytable;
    
            /*Innitialize variables*/
            mytable.size  = length;                               /*Size of the array (used for rfl function call)*/
            mytable.rem  = (length*fill);                        /*Remaining count of rfl table*/
            mytable->array = (int*)malloc(length * sizeof (int)); /*Allocate memroy*/
    
            if (mytable->array == NULL) /*Check progress of memory allocation*/
                    printf("ERROR! Could not allocate memory for table\n");
    
            for(i=0;i<length;i++)
                    mytable->array[i] = fill;
    
            return mytable; /*All is well*/
    }
    
     /*Remove the specified index, adjusting the count accordingly*/
     int remove( table *mytable, int index )
     {
             mytable.count -= table->array[index];
             mytable->array[index] = 0;
     }
    
    /*Increment existing values in array, increasing the count accordingly*/
     int increment( table *mytable )
     {
            int i;
    
            for(i=0;i<(mytable.size);i++)
            {
                    if(mytable->array[i])
                            mytable->array[i] += 1;
             }
     }
    
      /*Destructor - Free allocated memory and set pointer to null*/
      void delete( table *mytable )
      {
              free(mytable->array);  /*Free allocated memory*/
              mytable->array = NULL; /*Assign pointer to null*/
    
              mytable.count = 0;
              mytable.size = -1;
    
              if( mytable->array != NULL )
                   printf("ERROR! Could not de-allocate memory for table\n");
      }
    
    }
    If I want some other function to modify the contents of the structs "count" variable, can I just pass it like so: "&(mytable.count)", than have the function im passing it to modify it?

    Also, can I just use integers in the struct than modify them at will, or do I need them to be pointers and modify them another way?

  6. #6
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    The typedef and all your functions should be declared outside main.

    Few more things:
    Code:
    typedef struct table
    {
            /*Innitialize all values incase we use accidentally*/
            int *array = NULL; /*Default for pointers (points to nothing)*/
            int count = 0;    /*Default for counter (empty array)*/
            int size;
    };
    Ixnay. No initialization of variables in C struct definitions! This will not pass your compiler, even.* You can do that in your constructor function -- which, probably not by coincidence, it is traditional in C to call a function which takes care of constructor type things an "initialization function", eg. init_array().

    If I want some other function to modify the contents of the structs "count" variable, can I just pass it like so: "&(mytable.count)", than have the function im passing it to modify it?
    Yeah, if you want to do it that way, which is a good idea if the function only deals with one member of the struct:
    Code:
    void changeint (int *ptr);       /* prototype */
    changeint(&mytable.count);      /* example call   */
    Also, can I just use integers in the struct than modify them at will, or do I need them to be pointers and modify them another way?
    You can put any kind of datatype in a struct that you want: pointers, arrays, other structs, whatever. Just no functions!

    You understand the importance of memory allocation and cleanup, that is good.

    * you should always be testing and compiling code while you design. Even if it "does" nothing, this will still tell you if you are going the wrong way with your syntax, which you are to some extent.
    Last edited by MK27; 12-05-2009 at 10:02 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  7. #7
    Registered User
    Join Date
    Dec 2009
    Posts
    47
    Thanks so much for all the input. I've been stuck at work on a windows machine the whole weekend without a compiler :S, so all this has just been attempt and practice, monday I will be compiling and get a better idea of what i'm doing wrong.

    One thing I want to clear up, is both of my "table" variables are seperate? t1 and t2 do not share any of the data or memory? So modifying one will leave the other untouched? Or are they sharing the integers, but not the dynamically allocated array?

    It was mentioned putting function pointers within the struct, that may be interesting and make the code look better, but is it recommended? What are the pros and con's of doing this? It definately hides alot. what about using macros for the illusion of function overloading?

    I know im asking tons of questions, and thanks for all the help ive gotten so far.
    Last edited by tempster09; 12-05-2009 at 02:50 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling C in Visual Studio 2005
    By emanresu in forum C Programming
    Replies: 3
    Last Post: 11-16-2009, 03:25 AM
  2. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  3. Need help understanding info in a header file
    By hicpics in forum C Programming
    Replies: 8
    Last Post: 12-02-2005, 11:36 AM
  4. build errors migrated from dx9b to dx9c sdk
    By reanimated in forum Game Programming
    Replies: 4
    Last Post: 12-17-2004, 06:35 AM
  5. oh me oh my hash maps up the wazoo
    By DarkDays in forum C++ Programming
    Replies: 5
    Last Post: 11-30-2001, 11:54 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21