memcpy() and uint8_t

Discussion in 'C++' started by katty, Jan 18, 2010.

  1. katty

    katty New Member

    Joined:
    Jan 18, 2010
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Hello folks..

    In the following code, I m trying to copy struct element to array...


    Code:
    #include<iostream>
    #include<stdint.h>
    #include<string>
    
    using namespace std;
    struct test
    {
    	struct header
    	{
    		int a;
    		int b;
    	};
    	uint8_t c;
    	uint8_t d;
    	uint8_t e;
    	uint32_t f;
    };
    struct test2
    {
    	uint8_t n;
    	uint8_t m;
    	uint8_t p;
    };
    
    
    int main()
    {
    	test headd;
    	test2 data;
            uint8_t* d;
    	int x, y,i;
    
    	x= sizeof(test);
    	y= sizeof(test::header);
    	i= sizeof(data);
    
    	x=x+y+i;
    	d = new uint8_t[x+10];
    	cout<<"x ="<<x<<endl;
    
    /** Assign **/
    	headd.c = 4;
    	headd.d = 5;
    
    	data.n=8;
    	data.m=7;
    	data.p=9;
    
    /** copy 2 elements of struct 'headd' and struct 'data' on to memory block pointed by 'd' **/
    
    	memcpy(d,&headd.c,8); 
    	cout<<"d="<<*d<<endl; 
    	cout<<"d2="<<*(d+1)<<endl;
    
    	memcpy(d+8,&data, 8);
    	cout<<"d="<<*d<<endl;
    	cout<<"d2="<<*(d+2)<<endl;
    
    	return 0;
    }
    
    
    
    OUTPUT:
    x =19
    d=
    d2=
    d=
    d2=


    I ve replaced uint8_t and uint32_t by datatype 'int' and it works well... i can display contents of 'd'
    but not for uint8_t and uint32_t .
    Please suggest me how can i check whether data successfully copied to destination?


    Thank You
     
  2. Gene Poole

    Gene Poole New Member

    Joined:
    Nov 10, 2009
    Messages:
    93
    Likes Received:
    5
    Trophy Points:
    0
    I'm not sure what you are doing, but it might be a packing issue. By default, MS compilers line-up data in structure to an 8 byte boundary (makes it easier on the memory controller). You can override this behavior with the #pragma pack option:

    Code:
    
    [COLOR="Blue"]#pragma pack(push,1)[/COLOR]
    struct test
    {
    	struct header
    	{
    		int a;
    		int b;
    	};
    	uint8_t c;
    	uint8_t d;
    	uint8_t e;
    	uint32_t f;
    };
    struct test2
    {
    	uint8_t n;
    	uint8_t m;
    	uint8_t p;
    };
    [COLOR="Blue"]#pragma pack(pop)[/COLOR]
    
     
  3. katty

    katty New Member

    Joined:
    Jan 18, 2010
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    I want to copy struct test (except struct header) and struct test2 on to array pointed by 'd'

    I 'd put printf() to display *d instead of cout... its working

    Thanks for early reply


     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice