copy struct to buffer

Discussion in 'C++' started by tom, Sep 20, 2006.

  1. tom

    tom Guest

    how to copy struct to buffer?





    char * buffer;
    buffer=(char *)malloc(5*20);
    Data_O tt;
    strcpy(tt.Name1, "John ");
    strcpy(tt.Name2, "Brown ");
    memcpy(buffer + 0,(const void*)tt, sizeof (tt)); // dasn't work
    strcpy(tt.Name1, "Tom ");
    strcpy(tt.Name2, "Backer ");
    memcpy(buffer + 5,(const void*)tt, sizeof (tt)); // dasn't work
    ....

    struct Data_O
    {
    char Name1[10+1];
    char Name2[10+1];
    };


    t.
     
    tom, Sep 20, 2006
    #1
    1. Advertising

  2. tom

    heltena Guest


    > char * buffer;
    > buffer=(char *)malloc(5*20);
    > Data_O tt;
    > strcpy(tt.Name1, "John ");
    > strcpy(tt.Name2, "Brown ");
    > memcpy(buffer + 0,(const void*)tt, sizeof (tt)); // dasn't work


    tt is not a pointer, you must be use &tt.

    > strcpy(tt.Name1, "Tom ");
    > strcpy(tt.Name2, "Backer ");
    > memcpy(buffer + 5,(const void*)tt, sizeof (tt)); // dasn't work


    Why not buffer + sizeof(tt) ?

    Or:

    char* buffer = new char[5 * sizeof(Data_O) ];
    Data_O* tt = (Data_O*) buffer;
    strcpy(tt->Name1, "John..");
    strcpy(tt->Name2, "Brown");
    tt = (Data_O*) (buffer + sizeof(Data_O));
    strcpy(tt->Name1, "Tom");
    strcpy(tt->Name2, "Backer");
    ....
    delete[] buffer;
     
    heltena, Sep 20, 2006
    #2
    1. Advertising

  3. tom wrote:
    > how to copy struct to buffer?
    >
    >
    >
    >
    >
    > char * buffer;
    > buffer=(char *)malloc(5*20);
    > Data_O tt;
    > strcpy(tt.Name1, "John ");
    > strcpy(tt.Name2, "Brown ");


    Try this:

    memcpy(buffer, &tt, sizeof tt);

    > memcpy(buffer + 0,(const void*)tt, sizeof (tt)); // dasn't work
    > strcpy(tt.Name1, "Tom ");
    > strcpy(tt.Name2, "Backer ");
    > memcpy(buffer + 5,(const void*)tt, sizeof (tt)); // dasn't work


    memcpy(buffer + sizeof tt, &tt, sizeof tt);

    Krishanu
     
    Krishanu Debnath, Sep 20, 2006
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Chris Fogelklou
    Replies:
    36
    Views:
    1,392
    Chris Fogelklou
    Apr 20, 2004
  2. Alex
    Replies:
    2
    Views:
    1,238
  3. Replies:
    26
    Views:
    2,123
    Roland Pibinger
    Sep 1, 2006
  4. Tzury Bar Yochay
    Replies:
    4
    Views:
    576
    John Machin
    Sep 21, 2008
  5. Replies:
    1
    Views:
    314
Loading...

Share This Page