偏移指针的正确方法是什么?
我想传递一个指向函数的指针。我希望这个指针指向数组中间的某个位置。假设我有一个像 unsigned char BufferData[5000]; 这样的数组,下面的语句在语法上正确吗?
writeSECTOR( destAddress, (char *)( BufferData + (int)(i * 512 )) );
// destAddress is of type unsigned long
// writeSECTOR prototype: int writeSECTOR ( unsigned long a, char * p );
// i is an int
I want to pass a pointer to a function. I want this pointer to point to some place in the middle of an array. Say I have an array like such unsigned char BufferData[5000];
, would the following statement be correct syntactically?
writeSECTOR( destAddress, (char *)( BufferData + (int)(i * 512 )) );
// destAddress is of type unsigned long
// writeSECTOR prototype: int writeSECTOR ( unsigned long a, char * p );
// i is an int
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这样就可以了,但只需做到这一点:(
听起来 writeSECTOR 确实应该采用 unsigned char* )
That would do, but just make it:
(It sounds like writeSECTOR really should take an unsigned char* though)
指针算术相当容易理解。如果您有一个指向数组第一个元素的指针,则 p + 1 指向第二个元素,依此类推,无论每个元素的大小如何。因此,即使您有一个整数数组或任意结构 MyData,它也将成立。
如果您的数组是无符号字符,那么您只需添加您希望进入数组的字节偏移量,例如,
或者,如果符号令人困惑,您可以随时引用它,如上面注释中所示,例如
&数据[512]
Pointer arithmetic is fairly simple to understand. If you have a pointer to the first element of an array then p + 1 points to the second element and so on regardless of size of each element. So even if you had an array of ints, or an arbitrary structure MyData it would hold true.
If your array is unsigned char then you just add however many bytes offset you wish to go into the array, e.g.
Alternatively if the notation is confusing, you can always refer to it as it is shown in comments above, e.g.
&data[512]
您只需执行 BufferData + i * 512 即可。当您向 char* 添加整数值时,算术
+
运算符会生成 char*。You can just do
BufferData + i * 512
. An arithmetic+
operator on char* yields a char* when you add an integer value to it.那应该有效。在 C 语言中,向指针添加一个整数会使指针增加该整数乘以指针指向的类型的大小。
That should work. In C, adding an integer to a pointer increases the pointer by the integer multiplied by the
sizeof
the type the pointer points to.看起来不错,但是在编译器上尝试一下,
您可以使用 writeSECTOR( destAddress, &BufferData[i * 512] );
it looks ok, but try it on the compiler,
You can use writeSECTOR( destAddress, &BufferData[i * 512] );
看起来它将传入数组的第 i*512 个元素的地址。这就是你想要它做的吗?
我真的不明白转换为 int 会给你带来什么。
That looks like it will pass in the address of the i*512'th element of the array. Is that what you want it to do?
I don't really see what that cast to int is buying you though.
这应该像你想的那样工作。
C 中的指针只是 RAM 中的一个地址,因此您可以在测量中漂移指针。
That should work as you think.
Pointer in C is just an address in RAM,so you could drift the pointer in your measure.