简体   繁体   English

使用C语言将数组中的元素范围复制到另一个数组中

[英]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). 它将有一个填充了ID的本地整数数组(只是随机数)。 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. ptr指针将用于本地数组的起始地址。 first indicates where copying begins. 首先表明复制开始的地方。 last indicates where copying ends. last表示复制结束的位置。 Btw, i'm using code composer and working with MSP430. 顺便说一句,我正在使用代码编辑器并使用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. g_id是全局数组,但我无法弄清楚。

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) 最后不起作用,第一个是3,程序跳转到3个值,从8开始。(8,3,5,1,4,0​​,9,1,0,0,0)但我想看(0 ,0,0,8,3,5,1,4,0​​,0,0)

You are setting p = g_id . 你正在设置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;
}

To understand it better, use indexes instead of pointers: 要更好地理解它,请使用索引而不是指针:

for (int i = first; i <= last; i++) {
    g_id[i] = id[i];
}

Otherwise: 除此以外:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM