2013-10-20 64 views
1

我有一個大學項目需要將int轉換爲char的緩衝區。 我需要使用memcpy,但是當我複製這些值時不起作用,因爲msg_buf仍然是空的。 我有一些限制: - 我需要使用memcpy,因爲我的老師會像memcmp(msg_str,& opcode,2)== 0)一樣測試我的代碼。C中的緩衝區消息

這裏是我的代碼:

int message_to_buffer(struct message_t *msg, char **msg_buf){ 
    int opcode = htons(msg->opcode); 
    int c_type = htons(msg->c_type); 
    int result; 
    int buffer = sizeof(opcode) + sizeof(c_type); 

    switch(msg->c_type){ 

     case CT_RESULT: 

      result = htonl(msg->content.result); 
      buffer += sizeof(result); 
      *msg_buf = (char*)malloc(sizeof(char) * 12); 

      if(msg_buf == NULL) 
       return -1; 
      memcpy(*msg_buf,&opcode,sizeof(opcode)); 

      break; 

    }; 

    return buffer; 
} 

這裏有什麼問題?

+0

你能更具體地瞭解它是如何工作的嗎? – icktoofay

+0

操作碼的值不會被複制到緩衝區。 –

+0

你應該編輯你的評論,把它作爲一個大學項目加入到問題中,以便回答的人知道這些限制。截至目前,你所做的只是發佈代碼並說'它不起作用。' – 2013-10-20 01:50:28

回答

1

更具體地說,您需要複製短褲短褲,而不是整數。 sizeof(short)!= sizeof(int)(通常取決於體系結構):

int message_to_buffer(struct message_t *msg, char **msg_buf){ 
    short opcode = htons(msg->opcode); 
    short c_type = htons(msg->c_type); 
    int result; 
    char* buffer = NULL, *buf_start=NULL; 
    *msg_buf = NULL; 

    switch(msg->c_type){ 

     case CT_RESULT: 

      result = htonl(msg->content.result); 
      buffer = (char*)malloc(sizeof(char) * 12); 

      if (buffer == NULL) 
       return -1; 
      buf_start = buffer; 
      memcpy(buffer,&opcode,sizeof(opcode)); // sizeof(short) == 2; sizeof(int) == 4 
      buffer += sizeof(opcode); 
      memcpy(buffer,&c_type,sizeof(c_type)); // sizeof(short) == 2; sizeof(int) == 4 
      buffer += sizeof(c_type); 
      memcpy(buffer,&result, sizeof(result)); 
      buffer += sizeof(result); 
      *msg_buf = buf_start; 
      break; 

    }; 

    return buffer - buf_start; 
} 
+0

它的工作原理!非常感謝您的幫助。 –

0

爲什麼不使用itoa函數將int轉換爲char*?所以你用itoa函數替換你的memcpy

參考:http://www.cplusplus.com/reference/cstdlib/itoa/

[編輯] 如果你的編譯器不支持itoa,您可以使用sprintf代替。

+0

itoa不是標準功能 – sukhvir

+0

因爲我需要發送整個結構:
struct message_t { \t short opcode; \t short c_type; \t union content_u { \t \t struct entry_t * entry; \t \t char * key; \t \t char **鍵; \t \t struct data_t * value; \t \t int result; \t} content; }; –

+0

我不太明白。那麼如果你將'memcpy(* msg_buf,&opcode,sizeof(opcode));'改成'sprintf(* msg_buf,「%d」,opcode);'? – rcs

1

我認爲你的問題可能是你在int上調用htons()。 htons()意味着與short類型的值一起使用,所以你可能會丟失你的msg-> opcode和msg-> c_type的高16位。嘗試用htonl()替代htons()。另外,它看起來像是用malloc()分配一個12字節的緩衝區,但只寫入4個字節,而後者的8個字節未初始化/未定義。那是故意的嗎?

+0

我試過用htonl()和結果是一樣的。我分配一個12字節的緩衝區,因爲我需要複製更多的兩個int's –

相關問題