Results 1 to 2 of 2
Hi,guys:
I put two struct variables into a continuous memory at first by using memcpy(). And then I print out each variable's element. But sometimes it just prints out "0". ...
- 01-05-2012 #1Just Joined!
- Join Date
- Jan 2012
- Posts
- 1
Can not get valid value from Char* buffer
Hi,guys:
I put two struct variables into a continuous memory at first by using memcpy(). And then I print out each variable's element. But sometimes it just prints out "0". Can someone tell me the reason of that?
Thanks,
Code:#include <stdio.h> #include <stdlib.h> #include<string.h> #define message_size 100 typedef struct message message; struct message { message*prev; message*next; int recv; }; int main () { int kk; int position; message*test[2]; test[0] =(message*)malloc(sizeof(message)); test[1] =(message*)malloc(sizeof(message)); test[0]->recv=1; test[1]->recv=2; char*buffer=(char*)malloc(sizeof(message)*2*sizeof(char)); for(kk=0,position=0;kk<2;kk++,position+=sizeof(message)) memcpy(&buffer[position],test[kk],sizeof(message)); for(kk=0,position=0;kk<2;kk++,position+=sizeof(message)) { message*tmp=(message*)&buffer[position]; printf("recv is %d\n",tmp->recv); } }Last edited by elija; 01-06-2012 at 11:46 AM. Reason: Added code tags to make code more readable
- 01-07-2012 #2Just Joined!
- Join Date
- Aug 2011
- Posts
- 48
I tried your code on my Mac and it worked. I never got the 0 that your are getting. The only thing that I can think of is that the sizeof is or is not packing the size of the structure. Like for me the size of message is 24 bytes because my machine is 64-bit even though the size of message would be 12 on a 32-bit machine and 20 on a 64-bit machine.


Reply With Quote