【问题标题】:How can I print a struct and memcpy it?我怎样才能打印一个结构并 memcpy 呢?
【发布时间】:2019-11-04 17:41:19
【问题描述】:

我有以下结构 -

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 );

【问题讨论】:

  • 您是否尝试将结构转换为字符流?
  • @IvanGonzalez - 是的。我想将结构打印为字符流

标签: c struct


【解决方案1】:

您缺少内存分配。检查此代码并让我知道任何问题:

#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

数据实际上是复制的

【讨论】:

  • 在 C 中,不要将调用的返回值转换为堆分配函数:malloc()calloc()realloc()
  • 发布的数据只有在运行它的系统是little endian I.E.时才是正确的。 “大端”系统将显示截然不同(排序)的结果数据
  • 关于:for(int j=0; j&lt;8*sizeof(char); j++){ C 标准将sizeof(char) 定义为1。因此8*1 仍然是8
  • 输出:size of struct: 8 仅在底层硬件架构为 32 位时才为真。如果底层硬件架构是64位,那么value就是16,只输出前1/2的数据
  • 我添加了 8*sizeof(char) 以提高可读性。为什么不推荐铸造?我打印的数据仅供参考,我的目的不是为了显示一些参考。
猜你喜欢
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
  • 2021-04-20
  • 2022-10-24
  • 2018-10-05
  • 1970-01-01
  • 2023-02-06
  • 1970-01-01
相关资源
最近更新 更多