我在我的C源文件中创建了这样一个字节数组:
static char arr[64];我还声明了一个如下结构:
static char arr[64];
struct test {
int foo;
int data;
};如果内存中的所有内容都是字节,那么如何将test结构的字节存储在arr中?
我尝试了以下几点:
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数组中?
发布于 2022-02-15 13:49:06
您可以:
#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]);
}78 56 34 12
54 05 00 00(或大致如此,取决于endianness和struct对齐)。
发布于 2022-02-15 14:35:10
似乎你只是在寻找这样的东西:
(假设没有结构填充)
struct test {
int foo;
int data;
};
static struct test array [8] =
{
{ .foo = 123, .data = 456 }
...
};然后,对于任意类型的任意数据块,C允许我们使用字符指针检查它:
unsigned char* raw_data = (unsigned char*)&array;
...
raw_data[i] // access individual bytes因此,单独的64个字节数组没有任何用途。
或者,您可以这样做:
typedef struct {
int32_t x;
int32_t y;
} foo_t;
typedef union {
foo_t foo [8];
uint8_t bytes [64];
} bar_t;同样,这是假设没有填充(只有2个int的结构将没有任何)。
https://stackoverflow.com/questions/71127519
复制相似问题