[英]C pointer arithmetic and array access
I have a function that takes a pointer to an array of structs 我有一个函数,该函数需要一个指向结构数组的指针
typedef struct {
bool isUsed;
int count;
} MyStructure;
void Process(MyStructure *timeStamps, int arrayLength){
for (int i = 0; i < arrayLength; i++){
MyStructure *myStructure = &(*(timeStamps + i));
if (myStructure->isUsed == true){
/*do something*/
}
}
}
The way that I am accessing the array seems to be a little off. 我访问数组的方式似乎有些偏离。
&(*(timeStamps + i))
Is there a better way to do this? 有一个更好的方法吗?
&(*(timeStamps + i))
is equivalent with 等价于
&timeStamps[i]
which is, in turn, simply 反过来,这仅仅是
timeStamps + i
That's all :) 就这样 :)
The argument timeStamps
is of type MyStructure*
, which means that this line: 参数
timeStamps
的类型为MyStructure*
,这意味着此行:
MyStructure *myStructure = &(*(timeStamps + i));
is equivalent to: 等效于:
MyStructure *myStructure = timeStamps + i;
which is also equivalent to: 这也等效于:
MyStructure *myStructure = &timeStamps[i];
Note that in this expression: &(*(timeStamps + i))
, the timeStamps + i
is a pointer to the element at index i
(ie the address of this element), which is then dereferenced by using dereference operator ( *
) that returns an l-value of type MyStructure
and then you retrieve the address of this element by using the address-of operator ( &
) which is equal to the address that timeStamps + i
held at the beginning. 请注意,在此表达式中:
&(*(timeStamps + i))
, timeStamps + i
是指向索引i
处元素的指针(即该元素的地址),然后使用解引用运算符( *
) timeStamps + i
进行解引用 。返回MyStructure
类型的l值,然后使用地址运算符( &
)检索此元素的地址,该运算符等于timeStamps + i
开头的地址。
MyStructure *myStructure = &timeStamps[i];
Been a while since I worked in C, but as far as I remember the square brackets indexing operator ([]) is the same as adding to the pointer. 自从我使用C语言以来已经有一段时间了,但是据我所知,方括号索引运算符([])与添加到指针相同。 So:
所以:
timeStamps[i]
should be equivalent to *(timeStamps + i)
timeStamps[i]
应该等于*(timeStamps + i)
Therefore you should be able to use 因此,您应该能够使用
myStructure = &timeStamps[i]
I would suggest: 我会建议:
void Process(MyStructure *timeStamps, int arrayLength){
for (MyStructure *i = timeStamps; i < timeStamps + arrayLength; i++) {
if (i->isUsed == true) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.