1

Suppose I want to perform the following action in C. Is there a way to do this more efficiently with pointers (just out of interest, as I am in the process of learning C). Thanks!

int my_array[5];

my_array[0] = my_array[1];
my_array[1] = my_array[2];
my_array[2] = my_array[3];
my_array[3] = my_array[4];
my_array[4] = my_array[5];
my_array[5] = 0;
2
  • With modern compilers, array indexing code and pointer code often end up as nearly identical machine code. Just code it the way that makes most sense. I vote for for (int i = 0; i < 5; i++) my_array[i] = my_array[i+1]; my_array[5] = 0;. Commented Aug 30, 2014 at 2:15
  • 1
    you cannot use my_array[5] Commented Aug 30, 2014 at 9:01

2 Answers 2

3

use memmove.

memmove(&my_array[0], &my_array[1], 5 * sizeof(my_array[0]));
my_array[5] = 0;

Maybe it's the most efficient way, because in most case memmove is implemented with special machine code (e.g. rep movsd of x86, or SSE..)

(Notice that you cannot use memcpy, because the source and the destination are overlap. If you use memcpy, undefined behavior would come up.)

If you want to copy maually through pointer, you may want this:

int *p;
for (p = my_array; p < my_array + 5; p++)
    *p = *(p + 1);
*p = 0;
Sign up to request clarification or add additional context in comments.

Comments

1

You can do like this...

for(i=0;i<5;i++)
my_array[i]=my_array[i+1];
my_array[i]=0;

In array concept the most index is less than 1 of no of elements in that array.Here your array elements 5;But you are trying to access 5th index of array my_array[5]. Suppose if you do this operation after initializing array, then you 'll get garbage value in 4th index of array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.