0

Possible Duplicate:
Inserting characters in the middle of char array

I need to insert element in between 2 elements in a static array. I have written the following code. Please let me know if we have more efficient code than this.

int main()
{
    int a[4];

    a[0] = 10;
    a[1] = 20;
    a[2] = 30;

    int x = 15;

    memcpy(a+2,a+1,2);

    a[1] = x;

    printf("%d",a[2]);
}
Community
  • 1
  • 1
Anup Buchke
  • 5,210
  • 5
  • 22
  • 38

1 Answers1

1

You are worrying too much about low level optimizations - the compiler takes care of that.

If believe the most obvious code is also the fastest in this case:

a[3] = a[2];
a[2] = a[1];
a[1] = x;

You can't get it simpler than that.


Here is an example of what the compiler can do when optimizing code:

https://stackoverflow.com/a/11639305/597607

(10 lines of source code turned into 4-5 machine instructions - just let the compiler do its work!).

Community
  • 1
  • 1
Bo Persson
  • 90,663
  • 31
  • 146
  • 203