2012-02-04 44 views
1

好了,我把整个结构在这里,它的规范,在一些工业交换机实现的协议名为OpenFlow的,所以结构是这样的:填补了一个结构里的数组场

struct ofp_packet_in { 
    struct ofp_header header; 
    uint32_t buffer_id;  /* ID assigned by datapath. */ 
    uint16_t total_len;  /* Full length of frame. */ 
    uint16_t in_port;  /* Port on which frame was received. */ 
    uint8_t reason;   /* Reason packet is being sent (one of OFPR_*) */ 
    uint8_t pad; 
    uint8_t data[0];  /* Ethernet frame, halfway through 32-bit word, 
           so the IP header is 32-bit aligned. The 
           amount of data is inferred from the length 
           field in the header. Because of padding, 
           offsetof(struct ofp_packet_in, data) == 
           sizeof(struct ofp_packet_in) - 2. */ 
}; 
OFP_ASSERT(sizeof(struct ofp_packet_in) == 20); 

现在我必须填写最后一个字段中的一些数据,即 - uint8_t data[0],这些数据可以变化,并且信息从标题内的长度字段收集。我必须建立一个数据包,并且必须输入数据。请看看。

回答

1

您需要使用动态分配并复制内容。

喜欢的东西:

#include <stdlib.h> 
#include <string.h> 

void foo(void) { 
    struct some_struct *container = malloc(sizeof(struct some_struct) + 100); 
    if (!container) { 
    // handle out-of-memory situation 
    } 
    memcpy(container->data, some_data, 100); 
} 
+0

请再次看到问题,编辑它。 – Abdullah 2012-02-04 10:35:40

+0

我的答案适用于您更改的结构。用你需要的大小替换“+ 100”,并用'container-> data'来填充数据。 – Mat 2012-02-04 10:39:58

+0

@ Mat,thnx mate。欢呼:) – Abdullah 2012-02-04 16:47:10

0

你不能这样做。它不适合!结构中的数组长度为0个字符,并且您试图向其中填充一个100个字符的数组。

如果由于某种原因,您确定该结构之后的内存可用,例如,你只是malloc分配是这样的:

some_struct *foo = (some_struct*)malloc(sizeof(some_struct) + 100); 

然后,你可以这样做:

memcpy(foo->data, some_data, 100); 

这是可怕的,而且很可能仍然不确定的行为,但我已经看到了这个要求(的Windows API? )。

+0

这不是有效的,你没有为分配= foo.data>未定义行为的任​​何存储 – Mat 2012-02-04 10:01:25

+0

你说得对,我是个懒人我例。固定。 – Thomas 2012-02-04 10:04:00

+0

请再次看到问题,编辑它。 – Abdullah 2012-02-04 10:36:14

0

你不能。

您定义some_struct.data的大小为,这意味着它不能持有任何项目。
如果你想要的只是复制最大值。 100个项目到它,那么你可以定义静态大小:

struct some_struct { 
char data[100]; // some_struct.data has room for up to 100 characters 
}; 
+0

哦,对了,@马特的答案是你需要:-) – Maya 2012-02-04 10:23:20

+0

请再次看到问题,编辑它。 – Abdullah 2012-02-04 10:36:02