将值存储在指针var [英] Store value in pointer var

查看:118
本文介绍了将值存储在指针var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在* pData中存储int值并显示它的值?

  int id = 12; 
int age = 14;
unsigned char * pData = new unsigned char [8];
memcpy(pData,& id,4); / *使用memcpy复制* /
pData = pData + 4;
memcpy(pData,& age,4); / *使用memcpy拷贝* /
//如何从缓冲区打印值* pData
pre>

解决方案

使用 memcpy 复制 int 转换为unsigned char缓冲区,显示ints的唯一正确方法是将字节复制回int。例如:

  int temp_int; 
memcpy(& temp_int,pData,sizeof temp_int);
std :: cout<< temp_int<< '\\\
';
memcpy(& temp_int,pData + sizeof temp_int,sizeof temp_int);
std :: cout<< temp_int<< '\\\
';

尝试将缓冲区重新解释为 int 将通过违反严格别名规则导致未定义的行为。


How to store int values in *pData and display values from it?

  int id = 12;
  int age = 14;
  unsigned char* pData = new unsigned char[8];
  memcpy(pData,&id,4);/* using memcpy to copy */
  pData = pData + 4;
  memcpy(pData,&age,4);/* using memcpy to copy */
  // How to print value from buffer *pData

解决方案

After using memcpy to copy the bytes of an int into an unsigned char buffer, the only correct way to display the ints is to copy the bytes back into an int. For example:

int temp_int;
memcpy(&temp_int, pData, sizeof temp_int);
std::cout << temp_int << '\n';
memcpy(&temp_int, pData + sizeof temp_int, sizeof temp_int);
std::cout << temp_int << '\n';

Attempting to reinterpret the buffer as an int would cause undefined behaviour by violating the strict aliasing rule.

这篇关于将值存储在指针var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆