[英]How can I print a struct and memcpy it?
我有以下结构 -
struct data
{
unsigned char r;
int f;
};
然后我尝试打印它,但在打印语句中出现分段错误。 我做错了什么,我该如何做 memcpy 和 print ?
struct data *data1;
char temp[10];
data1->r = 1; data1->f = 2;
memcpy(temp,(char *)(struct data *)data1, sizeof(struct data));
printf("buffer is %s\n",temp );
您缺少内存的分配。 检查此代码,让我知道任何问题:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
struct data{
unsigned char r;
int f;
};
int main(){
struct data *data1=(struct data*)malloc(sizeof(struct data));
char temp[100];
data1->r = 255; data1->f = 1;
memcpy(temp, data1, sizeof(struct data));
printf("size of struct: %d\n", (int)sizeof(struct data));
printf("buffer is: \n");
//code to print the buffer in binary in chunks of 4
for(int i=0; i<sizeof(struct data); i++){
char v=temp[i];
for(int j=0; j<8*sizeof(char); j++){
if(v & 1)
printf("1");
else
printf("0");
v>>=1;
}
if((i+1)%4==0) printf("\n");
else printf(" ");
}
printf("\n");
};
输出:
size of struct: 8
buffer is:
11111111 00000000 00000000 00000000 //r
10000000 00000000 00000000 00000000 //f
数据实际上是复制的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.