2012-02-04 39 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

相關問題