简体   繁体   中英

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++; increments both dstptr and srcptr by one once. But I need to increment them by two. Is there any clue how to do this in 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 .

Also as @unwind mentioned, you have to assign some dynamical memory to pointers otherwise dereferencing would cause undefined behavior.

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];
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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