这两个涉及指针运算的语句有什么区别?
假设之间有什么区别
char cur_byte=*((char *)(buf+i));
和
char *b=(char *)(buf);
char cur_byte=*(b+i);
: buf 是一个指向 void 的指针 // void *buf;和 i 用作 for 循环中的迭代器 我在 ac 源代码中找到了生成拉宾指纹的代码(第一行),因为 VC2010 Express 将其报告为错误,所以我必须将其替换为后两行。而且我不确定它是否可以达到预期目的。另外,如果有人能给我提示在哪里可以获取用于内容定义分块和指纹生成的有效 C++ 源代码,我将不胜感激。
What is the difference between
char cur_byte=*((char *)(buf+i));
and
char *b=(char *)(buf);
char cur_byte=*(b+i);
Assume:
buf is a pointer to void// void *buf; and
i is used as an iterator in a for loop
I found this code(the first line) in a c source code which generates rabin fingerprints and because VC2010 express reported it as an error I had to replace it with the second two lines. And I am not sure if it can do the intended purpose. Plus I would be grateful if anyone can give me a hint where to get a working C++ source code for content defined chunking and fingerprint generating.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在第一个语句中,您将一个整数(
i
是整数类型,对吧?)添加到void*
,然后转换为char*
。使用 void 指针的指针算术不是由 C 标准定义的,因为编译器无法知道应该将指针增加多少。然而,有些编译器定义了sizeof(void) == 1
。在这种情况下,您的两个代码片段是等效的,这解释了为什么此代码可能与另一个编译器一起工作(感谢 Steve Jessop 指出这一点)。你在第一个片段中的意思可能是
char cur_byte=*(((char *) buf) + i);
,位于buf后i
个字符的地址所指向的字符。在以下架构中,其中
i==4
、cur_byte
将被分配值r
。在第二条语句中:
首先将
buf
分配给b
,然后将b + i
的内容分配给cur_byte
。b
的类型为char*
,因此添加i
将会在b
之后给出地址i
个字符>。最后这两个语句是等价的(除了
b
的赋值)。In your first statement you add an integer (
i
is an integer type, right?) to avoid*
, casting tochar*
afterwards. Pointer arithmetic with void pointers is not defined by the C standard, because the compiler has no way to know of how much it should increment the pointer. Some compilers, however, definesizeof(void) == 1
. In this case, your two snippets are equivalent, which explains why this code may have worked with another compiler (thanks Steve Jessop for pointing this).What you meant in your first snippet was probably
char cur_byte=*(((char *) buf) + i);
, the character pointed by the address locatedi
characters after buf.In the following schema, where
i==4
,cur_byte
would be assigned the valuer
.In your second statement:
you first assign
buf
tob
, and then assign the content ofb + i
tocur_byte
.b
has typechar*
so addingi
will give the addressi
characters afterb
.In the end these two statements are equivalent (except for the assignment of
b
).区别在于表达式
(buf + i)
与(b + i)
。b
的类型为char*
,因此(b + i)
将指向b + sizeof(char) * i
。buf
可以是不同的类型,因此(buf + i)
将指向buf + sizeof(BUFS_TYPE) * i
。The difference is in the expressions
(buf + i)
versus(b + i)
.b
is of typechar*
so(b + i)
will point tob + sizeof(char) * i
.buf
could be of a different type so(buf + i)
will point tobuf + sizeof(BUFS_TYPE) * i
.