nisha
nisha

Reputation: 69

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?

Upvotes: 1

Views: 4171

Answers (2)

kocica
kocica

Reputation: 6465

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);

Upvotes: 3

Lundin
Lundin

Reputation: 214780

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

Upvotes: 3

Related Questions