# how can I handle a buffer???

• 03-19-2002
Unregistered
how can I handle a buffer???
Hi there....\n\n

Suppose we have a pointer if void type which we use then to allocate memory and create a buffer....

the buffer ,lets say has at first a string of 10 chars then a float and then and integer....

How I can access and print the fields of it?

My thought was to use a second pointer and allocate memory to him so it can hold the proper field and then copy on him the data but it does not work....

Whats wrong?

I thank "apriori" anyone for his good mood of helping me....
• 03-19-2002
Unregistered
Greetings,

You could use a union, for example:

Code:

```#include <iostream> // This structure will hold a string/int/float element struct element {     int type              // This will allow us to know what we have     union {         char* str;         int  i;         float f;     }; }; int main() {     element *elarray = new element [4];     element e;     // Im using 0=String; 1=Integer; 2=Float     e.type = 0;     e.str = new char [10];     strcpy(e.str, "Testing");     elarray[0] = e;                    // Set the 1st element     e.type = 1;                          // This one is an int     e.i = 1000;            elarray[1] = e;     e.type = 2;                          // And this one a float     e.f = 5.5f;     elarray[2] = e;     // Loop through the array displaying the type and value of     // the element     std::cout << "Type\t\tValue\n";     for (int i=0;i<3;i++) {         switch(elarray[i].type) {             case 0:                 std::cout << "String\t\t" << elarray[i].str << std::endl;                 break;             case 1:                 std::cout << "Integer\t\t" << elarray[i].i << std::endl;                 break;             case 2:                 std::cout << "Float\t\t" << elarray[i].f << std::endl;                 break;         }     }     delete [] elarray; }```
This works, but if you want a much more elegant and functional solution you should take a look at www.boost.org look at the file "any.hpp".