我不明白一些旧的 C 数组串联
我不明白这个旧的 C
程序中的语法,并且没有设置测试代码以了解它的作用。我感到困惑的部分是与数组的串联。我不认为 C 可以像那样处理自动类型转换,或者我是否让它在我的脑海中变得太困难,因为现在是星期五下午......
char wrkbuf[1024];
int r;
//Some other code
//Below, Vrec is a 4 byte struct
memcpy( &Vrec, wrkbuf + r, 4 );
知道这里会发生什么吗?当您连接或添加 int 时,wrkbuf
会变成什么?
I don't understand this syntax in this old C
program, and am not set up to test the code to see what it does. The part I am confused about is the concatenation to the array. I didn't think C could handle auto-typecasting like that, or am I making it too difficult in my head being that its Friday afternoon...
char wrkbuf[1024];
int r;
//Some other code
//Below, Vrec is a 4 byte struct
memcpy( &Vrec, wrkbuf + r, 4 );
Any idea what will happen here? What does wrkbuf
become when you concatenate or add an int to it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
memcpy(&Vrec, wrkbuf + r, 4)
将wrkbuf
的第r
位置的 4 个字节复制到Vrec< /代码>。当您将 int 添加到数组时,您将获得其第 r 个位置的内存地址,在本例中为
&wrkbuf[r]
。示例
memcpy
C 实现(如您所见,它与strcpy
非常相似):请参阅:
memcpy(&Vrec, wrkbuf + r, 4)
copies 4 bytes from ther
-th position ofwrkbuf
intoVrec
. When you add an int to an array, you get the memory addresss of ther
-th position of it, in this case,&wrkbuf[r]
.Sample
memcpy
C implementation (as you can see, it is quite similar tostrcpy
):See:
wrkbuf + r
与&wrkbuf[r]
相同当在表达式
wrkbuf + 4
中使用时,本质上是wrkbuf
code>“衰减”为指向第一个元素的指针。然后向其中添加r
,这将使指针前进r
元素。即这里没有进行连接,它正在执行指针算术。memcpy( &Vrec, wrkbuf + r, 4 );
从 wrkbuf 数组中复制 4 个字节,从第r
元素开始复制到的内存空间中弗雷克
wrkbuf + r
is the same as&wrkbuf[r]
Essentially
wrkbuf
when used as in the expressionwrkbuf + 4
"decays" into a pointer to the first element. You then addr
to it, which advances the pointer byr
elements. i.e. there's no concatenation going on here, it's doing pointer arithmetic.The
memcpy( &Vrec, wrkbuf + r, 4 );
copies 4 bytes from the wrkbuf array , starting at ther
th element into the memory space ofVrec