Thread: how can I handle a buffer???

  1. #1

    Unhappy 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....

  2. #2

    You could use a union, for example:

    #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;
                case 1:
                    std::cout << "Integer\t\t" << elarray[i].i << std::endl;
                case 2:
                    std::cout << "Float\t\t" << elarray[i].f << std::endl;
        delete [] elarray;
    This works, but if you want a much more elegant and functional solution you should take a look at look at the file "any.hpp".

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. writing a file from buffer
    By mariano_donati in forum C Programming
    Replies: 8
    Last Post: 02-25-2008, 02:04 AM
  2. Replies: 15
    Last Post: 10-31-2005, 08:29 AM
  3. Help with threading
    By crazeinc in forum C Programming
    Replies: 2
    Last Post: 06-02-2005, 05:23 PM
  4. DirectSound - multiple sounds
    By Magos in forum Game Programming
    Replies: 9
    Last Post: 03-03-2004, 04:33 PM
  5. Console Screen Buffer
    By GaPe in forum Windows Programming
    Replies: 0
    Last Post: 02-06-2003, 05:15 AM