Home > Software engineering >  How Could I Store A Struct In Char A Byte Array
How Could I Store A Struct In Char A Byte Array

Time:02-16

I have a byte array created like this in my C source file:

static char arr[64];

I also have a struct declared like so:

static char arr[64];

struct test {
    int foo;
    int data;
};

If everything in memory is just bytes, how could I store the bytes of of a test struct inside of arr

I have tried the following things:

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.
}

Is there any easy way that I can store the bytes of the test struct in the byte array arr so that I can store multiple structures in this array and access it easily too? If everything is just bytes, is there a feasible way to store the test struct bytes in the arr array?

CodePudding user response:

You can:

#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("x x x x\n", arr[0], arr[1], arr[2], arr[3]);
    printf("x x x x\n", arr[4], arr[5], arr[6], arr[7]);
}

This prints out

78 56 34 12
54 05 00 00

(or thereabouts, depending on endianness and struct alignment).

CodePudding user response:

It would seem that you are simply looking for this:
(assuming no struct padding ever present)

struct test {
  int foo;
  int data;
};

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

Then for any random chunk of data of any type, C allows us to inspect it with a character pointer:

unsigned char* raw_data = (unsigned char*)&array;
...
raw_data[i] // access individual bytes

So the separate 64 byte array fills no purpose.


Alternatively, you could do this:

typedef struct {
  int32_t x;
  int32_t y;
} foo_t;

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

Again, this is assuming no padding (a struct with just 2 int won't have any).

  • Related