简体   繁体   English

如何将C指针加2

[英]How to increment a C pointer by two

Here is my sample code: 这是我的示例代码:

float *dstptr;
float *srcptr;
float A[100];
float B[32];
int main(void)
  {
 int i=0;
 while(i < NUM_ITERATION)
  {
    srcptr = &B[0];
    for(i=0; i< 32; i++)
    {
        *dstptr++ = *srcptr++;
        dstptr = circptr(dstptr,1,(float *)&A[0], 100);
    }
    i++;
}

return 0;
}

Here *dstptr++ = *srcptr++; 这里*dstptr++ = *srcptr++; increments both dstptr and srcptr by one once. dstptrsrcptr都增加一次。 But I need to increment them by two. 但是我需要将它们增加两个。 Is there any clue how to do this in C? 有什么线索可以在C中执行此操作吗?

Its called pointer arithmetic 它称为指针算法

And it allows you to do 它可以让你做

dstptr += nOfElementsToSkip;
srcptr += nOfElementsToSkip;
*dstptr = *srcptr;

as well as incrementing. 以及递增。 Or if you dont want to modify the pointer 或者,如果您不想修改指针

*(dstptr+nOfElementsToSkip) = *(srcptr+nOfElementsToSkip); // Same as
dstptr[nOfElementsToSkip] = srcptr[nOfElementsToSkip];     // This is more clear

EDIT : 编辑

In your case change nOfElementsToSkip to 2 . 在您的情况下,将nOfElementsToSkip更改为2

Also as @unwind mentioned, you have to assign some dynamical memory to pointers otherwise dereferencing would cause undefined behavior. 同样如@unwind所述,您必须为指针分配一些动态内存,否则取消引用会导致未定义的行为。

float *dstptr = malloc(sizeof(float) * NUM_ITERATION);
// Do something with pointer
// And if you dont need them anymore
free(dstptr);

Preferably by not mixing several operators in the same expression, which is dangerous and sometimes hard to read. 最好不要在同一表达式中混用多个运算符,这很危险,有时很难阅读。 Instead, do this: 相反,请执行以下操作:

*dstptr = *srcptr;
dstptr += 2;
srcptr += 2;

Alternatively, use the most readable form, if this is an option: 或者,如果可以选择的话,使用最易读的形式:

for(size_t i=0; i<n; i+=2)
{
  ...
  dstptr[i] = srcptr[i];
  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM