首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将结构存储在Char A Byte数组中

如何将结构存储在Char A Byte数组中
EN

Stack Overflow用户
提问于 2022-02-15 13:43:41
回答 2查看 161关注 0票数 0

我在我的C源文件中创建了这样一个字节数组:

代码语言:javascript
复制
static char arr[64];

我还声明了一个如下结构:

代码语言:javascript
复制
static char arr[64];

struct test {
    int foo;
    int data;
};

如果内存中的所有内容都是字节,那么如何将test结构的字节存储在arr中?

我尝试了以下几点:

代码语言:javascript
复制
int main() {
    struct test t;
    t.foo = 255;
    t.data = 364;

    arr[0] = t; // This did not work; I got a type-mismatch

    // I also tried memcpy

    memcpy(arr, &t, 8); // But this did not work either because it does not store the data in array. I was also not able to deference the bytes that did get stored.
}

有什么简单的方法可以将test结构的字节存储在字节数组arr中,这样就可以在这个数组中存储多个结构并轻松地访问它吗?如果一切都是字节,那么是否有一种可行的方法将test结构字节存储在arr数组中?

EN

回答 2

Stack Overflow用户

发布于 2022-02-15 13:49:06

您可以:

代码语言:javascript
复制
#include <stdio.h>
#include <string.h>

struct test {
    int foo;
    int data;
};
int main() {
    struct test t;
    char arr[sizeof(struct test)];
    t.foo = 0x12345678;
    t.data = 1364;
    memcpy(arr, &t, sizeof(struct test));
    printf("%02x %02x %02x %02x\n", arr[0], arr[1], arr[2], arr[3]);
    printf("%02x %02x %02x %02x\n", arr[4], arr[5], arr[6], arr[7]);
}

这个打印出来

代码语言:javascript
复制
78 56 34 12
54 05 00 00

(或大致如此,取决于endianness和struct对齐)。

票数 1
EN

Stack Overflow用户

发布于 2022-02-15 14:35:10

似乎你只是在寻找这样的东西:

(假设没有结构填充)

代码语言:javascript
复制
struct test {
  int foo;
  int data;
};

static struct test array [8] =
{
  { .foo = 123, .data = 456 }
  ...
};

然后,对于任意类型的任意数据块,C允许我们使用字符指针检查它:

代码语言:javascript
复制
unsigned char* raw_data = (unsigned char*)&array;
...
raw_data[i] // access individual bytes

因此,单独的64个字节数组没有任何用途。

或者,您可以这样做:

代码语言:javascript
复制
typedef struct {
  int32_t x;
  int32_t y;
} foo_t;

typedef union {
  foo_t   foo   [8];
  uint8_t bytes [64];
} bar_t;

同样,这是假设没有填充(只有2个int的结构将没有任何)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71127519

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档