Use the same array functions for int and float (in C)

Hi, I have a file with functions to create arrays and handle array operations, and in my program I need to be able to create arrays of int or float. How can I use the same file for creating and working with various array types?

In "iarray.h", I put the definitions for int arrays type:
#include "array.h"
#define ARRAY_TYPE int
#define ARRAY_NAME iarray

And I include "iarray.h" in the src file that needs int arrays. But if I need to include "float.h" as well (in the same src file), it won't work this approach.

I will much appreciate any help.

Thanks in advance!

Comments

  • Here is a simple example of what I explained above. In main(), I need to use both data types (iarray and farray), so it won't work this way.
    [code]
    /* file: array.h*/
    #define ARRAY_NAME iarray
    #define ARRAY_TYPE int

    typedef struct array_s ARRAY_NAME;
    struct array_s{
    ARRAY_TYPE val;
    };

    /* file: array.c*/
    #include "array.h"

    ARRAY_TYPE testme(ARRAY_NAME st){
    return (st.val*2);
    }

    /* file: iarray.h*/
    #include "array.h"
    #undef ARRAY_NAME
    #undef ARRAY_TYPE
    #define ARRAY_NAME iarray
    #define ARRAY_TYPE int

    /* file: farray.h*/
    #include "array.h"
    #undef ARRAY_NAME
    #undef ARRAY_TYPE
    #define ARRAY_NAME farray
    #define ARRAY_TYPE float

    /* file: main.c */
    #include "iarray.h"
    //#include "faray.h"

    int main(){
    iarray my_i;
    //farray my_f;

    my_i.val=4;
    //my_f.val=5.2;
    printf("int value: %d
    ",testme(my_i));
    //printf("float value: %f
    ",testme(my_f));
    }

    [/code]
  • Umm... I don't understand what you mean. Where is the arrays and what do you want to do with them?
  • Sorry, the example maybe confused a bit. I need to use sparse arrays, so I use a struct for that, it has an array of ints (to store the indices of the sparse array), and an array of values (the values that correspond to the indices). The values can be of type int or float. (in the example, the struct for a sparse array I only included the values' array, no indices, to not complicate it)

    In array.c, I define many functions to work with the arrays, such as resize, search for values, addition, etc. But some of these functions need to know the type of values in the array (int or float). In the functions, I use ARRAY_TYPE where it's needed, which is defined in a header file:
    e.g. farray.h
    #define ARRAY_TYPE float

    The problem is this way I can't include farray.h and iarray.h as well, because the definitions in one of them will be overwritten. Thus I don't know how I could use both farray and iarray in the same file (e.g. main.c above).



Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion