模拟

/******************************************************************************************************
 * @file name:		  :Simulation(malloc)
 * @brief  		      :模拟获取数据,把首地址返回
 * @author 		      :wvjnuhhail@126.com
 * @date 			  :2024/06/24
 * @version 1.0 	  :V1.0
 * @property 		  :暂无
 * @note   		      :None
 * CopyRight (c)  2023-2024   wvjnuhhail@126.com   All Right Reseverd
 ******************************************************************************************************/

/***********************************************头文件******************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/**********************************************END*******************************************************/

/*
 *     使用malloc申请30个字节,模拟报文传输
 *  用这个30字节的空间来存放报文数据,报文数据:前4个字节存放正文段的字节大小,
 *  接下来的9个字节存放发送者的名字(旦丁),剩余的空间存放(hello Dante)正文
 *
 */

/***********************************宏定义***************************************************************/
#define MESSAGE_LEN 30
#define TEXT_SIZE_POS 0
#define SENDER_POS 5
#define TEXT_POS 12
/***********************************END*****************************************************************/

/********************************************************************************************************
 * @function_name   :	Get_Message_Data
 * @brief           : 模拟获取数据
 * @param           : NONE
 * @retval          : void
 * @date 			      :2024/06/24
 * @version         :V1.0
 * @note   		      :None
 *******************************************************************************************************/

char *Get_Message_Data()
{
  char *message_data_p = (char *)malloc(sizeof(char) * MESSAGE_LEN);
  if (message_data_p == (char *)NULL)
  {
    printf("申请存放报文数据堆空间失败!\n");
    return (char *)NULL;
  }

  memset(message_data_p, 0, sizeof(char) * MESSAGE_LEN);

  // 在前4个字节中存放数据的大小 11
  char Name[] = "但丁";
  char text[] = "hello dante";
  int text_len = strlen(text);

  memcpy(message_data_p + TEXT_SIZE_POS, &text_len, sizeof(int));
  memcpy(message_data_p + SENDER_POS, Name, strlen(Name));
  memcpy(message_data_p + TEXT_POS, text, text_len);

  return message_data_p;
}

int main()
{

  char *message_data_p = Get_Message_Data();
  if (message_data_p == (char *)NULL)
  {
    perror("获取报文数据失败!\n");
    exit(1);
  }

  printf("获取报文数据成功,如下:\n");
  printf("[data size: %d byte]\n", *((int *)message_data_p + TEXT_SIZE_POS));
  printf("[Sender: %s]\n", message_data_p + SENDER_POS);
  printf("[message data 数据正文: %s]\n", message_data_p + TEXT_POS);

  free(message_data_p);
  return 0;
}
posted @ 2024-06-24 23:57  WJnuHhail  阅读(2)  评论(0编辑  收藏  举报