Search code examples
carrayspointerscode-composer

copy range of elements from an array to another array in C language


i want to copy range of elements from existing array to new array. It will have a local integer array filled with an ID(just random numbers). It also has a global empty array having the same number of elements with the local array. My program contains a function, which copies the range of entries of the local array to the global array. this function will be as:

void func(int *ptr, int first, int last);

The ptr pointer will be used for the starting address of the local array. first indicates where copying begins. last indicates where copying ends. Btw, i'm using code composer and working with MSP430. Here is my code,

#include <msp430.h> 

int g_id[11];
int *ptr;
int *p;


int main(void) {

    WDTCTL = WDTPW | WDTHOLD;   // Stop watchdog timer
    
    int id[11]={5,0,1,8,3,5,1,4,0,9,1};
    int first = 3;
    int last= 8;
    ptr = id;
    p = g_id;

    for(ptr=&id[first]; *ptr < &id[last]; ptr++)
        {
            *p = *ptr;
            p++;         
        }

    while(1);
}

g_id is global array but i couldn't figure out.

last doesn't work and first was 3, program jump to 3 values and start with 8. (8,3,5,1,4,0,9,1,0,0,0) but i want to see (0,0,0,8,3,5,1,4,0,0,0)


Solution

  • You are setting p = g_id. If you want the copy to go to matching locations, you have to set matching offsets on both the local and global arrays.

    int *src, *dst;
    
    for (src = id + first, dst = g_id + first; src <= id + last; src++, dst++) {
        *dst = *src;
    }