AntikM
AntikM

Reputation: 651

C - Move array elements up with pointers

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;

Upvotes: 1

Views: 2663

Answers (2)

Anbu.Sankar
Anbu.Sankar

Reputation: 1346

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.

Upvotes: 1

ikh
ikh

Reputation: 10417

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;

Upvotes: 3

Related Questions