I have one question, and can not figure out how to do that after googling. I define a struct and use to allocate a memory block 4 alignment.
typedef struct
{
unsigned int param_len;
char param[1]; /* variable size array - param_len bytes */
/* Up to 3 pad bytes follow here - to make the whole struct int aligned. */
} test_t;
test_t test;
test.param_len = 5; /* set param_len = 5 */
int alloc_len = ((test.param_len % 4) + 1) * 4; /* 8 for int aligned */
unsigned char *block = malloc (alloc_len); /* allocate 8 bytes */
how to assign the param to the 8 bytes memory block as the following diagram?
+------------+
| param_len | int aligned
| param[1] | 8 bytes
| |
+------------+
If I do that:
&test.param[0] = block;
gcc complains error: lvalue required as left operand of assignment
If I do that:
test.param = block;
gcc complains error: assignment to expression with array type
Can any one help me to solve this problem? Thanks in advance.
EDIT:
My real question is how to write a code to assign a block of memory to the variable param1 and then send test by socket. So I try to use &test.param[0] = block;
, but gcc complains lvalue required
.
Solution:
After asking my classmate Daniel, he uses another apporach and then writes a test code sample_alloc.c for me. That what I real want.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
unsigned int param_len;
char param[1]; /* variable size array - param_len bytes */
/* Up to 3 pad bytes follow here - to make the whole struct int aligned. */
} test_t;
int main() {
int param_len=5;
int alloc_len = sizeof(unsigned int) + ((param_len % 4) + 1) * 4; /* 8 for int aligned */
unsigned char *block = malloc (alloc_len); /* allocate 4 + 8 bytes */
test_t *p=(test_t *)block;
p->param_len = param_len;
memcpy(p->param ,"Hello", 6);
printf("%d %s\n", p->param_len, p->param);
}
Thanks, Daniel!