【问题标题】:Unsigned char * added with int? What does this do?Unsigned char * 添加了 int?这是做什么的?
【发布时间】:2019-08-03 11:40:21
【问题描述】:

我一直在努力将一些代码从 c++(我可以体面地阅读的语言)转换为 Python(我可以很好地编写的语言),但遇到了一些让我非常困惑的行:

unsigned char byte = *(bytes+currentByte);
float * pF = (float*)(bytes+currentByte);
std::string str((char*)(bytes+currentByte), numBytes);

现在,这些行一开始看起来很正常,直到我确切地意识到变量是如何定义的:

// From the .h file
unsigned char* bytes;
int currentByte;

所以因为我不明白最终会发生什么,所以我不能希望转换代码。

谁能向我解释一下添加unsigned char *int 会做什么?谢谢。

【问题讨论】:

标签: c++


【解决方案1】:

*(bytes+currentByte)bytes[currentByte] 的另一种写法。这只是地址算术,当数组表示法更清晰易读时也有点可笑。

(float*)(bytes+currentByte) 表达式将bytes[currentByte] 的地址转换为浮点指针或(float*) &bytes[currentByte]

地址算法允许您将bytes[currentByte] 转换为currentByte[bytes],因为*(bytes+currentByte) 等价于*(currentByte+bytes)。它是“语法糖”,允许更清晰或更简洁的写作风格。这些都是等价的,而且是一个非常愚蠢的程序员技巧。

【讨论】:

  • 这太奇怪了,因为他们之前确实使用了这个精确的符号unsigned char byte = bytes[currentByte];
  • 值得注意的是,如果您有一个指向大于 char 的指针,则 +1 不会将指针“增加 1 个字节”,而是将其作为“1 个元素”,这意味着在这种情况下,2+2 可能与 4 不同。所以是的,这很令人困惑,最好使用 []
  • 在这种情况下,我觉得浮动指针实际​​上是这样有意义的。这将是一个浮点数,其指针与存储在 (bytes+currentByte) 的指针相同,对吗?还是float * pF = (float*)(bytes+currentByte); 仍然与float * pF = (float*)&bytes[currentByte]; 相同?
  • @TheElementalofCreation (float*)(bytes+currentByte) 会将bytes[currentByte] 的地址转换为浮点指针或(float*) &bytes[currentByte]
  • @Blastfurnace 哦,是的。这就是我的意思
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-26
  • 1970-01-01
  • 1970-01-01
  • 2014-01-29
  • 1970-01-01
  • 2012-11-27
相关资源
最近更新 更多