views:

96

answers:

3

Hello,

I have list of 5 elements. I get first element of this list. How can i kwno what's the data type of this element char* or int*?

Thank you

+1  A: 

In C, there is no (portable) way to find out if all you have is a void*. So you have to keep track about it yourself, when you store the elements into the list. Another possibility is to use type-specific lists instead of a generic void* list.

Secure
A: 

What do you mean by "list" here?

Is it:

   sometype* lst;

i.e. an array, or:

node* lst;

A linked list?

In the first case, sometype defines the type of elements in the array, unless it's some kind of a void* which means that the compiler doesn't know the type but the programmer (hopefully) does. In the second case you should look into the definition of node, it should contain data with typing information of some sort (and the void* argument from above applies).

Eli Bendersky
+1  A: 

You can't.

Either use type-specific lists (one list for your char-pointers, one list for your ints) or use a structure or union to store both types of values with a field that indicates the type, like this:

#define TYPE_INT    1
#define TYPE_STRING 2

struct MyValue
{
int type;        // TYPE_INT or TYPE_STRING
union
   {
   char *str;
   int   i;
   } value;
};

And store this struct into your list.

If C++ is an option, consider using std::list to store type specific data, or if this is not possible, define a class similar to the struct above in which you shield the different data types, like this (not including error checking on the type):

class MyValue
   {
   public:
      enum ValueType
         {
         TYPE_NONE;
         TYPE_INT,
         TYPE_STRING
         };
      MyValue() : m_type(TYPE_NONE) {}
      MyValue(char *s) : m_type(TYPE_STRING), m_value.str(s) {}
      MyValue(int i) : m_type(TYPE_INT), m_value.int(i) {}
      ValueType getType() const {return m_type;}
      const char *getString() const {return m_value.str;}
      int getInt() const {return m_value.int;}
   private:
      ValueType m_type;
      union InternalValue
         {
         char *str;
         int   i;
         };
      InternalValue m_value;
   };
Patrick
Why not `enum` instead of `#define`?
Georg Fritzsche
@Georg, this is because in my old C days, we couldn't use enums, only defines. I agree, enums are better.
Patrick