gpt4 book ai didi

c - 如何将数组的内容复制到两个大小不等的较小数组中

转载 作者:太空宇宙 更新时间:2023-11-04 01:17:20 25 4
gpt4 key购买 nike

我正在尝试将一个较大数组的内容复制到两个大小不等的较小数组(其大小可能会根据程序而变化)。我在下面的简化代码中有四个数组:

#define size 20
double bigArray[size]={14.553,13.653,9.555,8.564..and so on...9.324,11.123};
/*IndicatorArray is associated to bigArray as follows:
if bigArray[i]<10 then indicatorArray[i]=10 else =20 */
int indicatorArray[size]={20,20,10,10,..and so on..};
double array10[count10], array20[count20]; /*count10 and count20 are
counters from indicatorArray passed as a size of each array
in earlier function not shown here*/
for (i=0;i<size;i++){
if (indicatorArray[i]==10) {
arr10[i]=bigArray[i];
// printf("%lf ",arr10[i]); /*this shows me correct results*/
}
else {
arr20[i]=bigArray[i];
}
}
for (i=0;i<count10;i++){
printf("%lf ",arr10[i]);
}
printf("\n \n");
for (i=0;i<count20;i++){
printf("%lf ",arr20[i]);
}

结果是这样的

00.0000 00.0000 9.555 8.564 11.123 14.666 ....

14.553 13.653 00.000......00.000

但我不希望出现零或产生如此困惑的结果,而是像

9.55 8.564 ...... 7.123和14.533 13.653 .....11.123

为什么会发生这种情况以及如何以正确的方式做到这一点?

最佳答案

如评论中所述,拆分数组内容时,识别每个元素位于内存中特定的可寻址位置,这对来说是一项完美的工作memcpy() 。这是使用该概念的简单说明:

int main(void)
{
double source[] = {3.4,5.6,2.3,4.5,6.7,8.9,10.1,11.1,12.3,4.5};
double split1[3];
double split2[7];

memcpy(split1, &source[0], 3*sizeof(double));
memcpy(split2, &source[3], 7*sizeof(double));

return 0;
}

如果您的项目具有在运行时已知的明确定义和静态参数,那么使用一些通用宏和一些额外的变量,这可以变得更通用一些。

以下示例与上图基本相同,但在一个循环中,可能是一个更具适应性的构造。

#define SPLIT_CNT 3

int main(void)
{
double source[] = {3.4,5.6,2.3,4.5,6.7,8.9,10.1,11.1,12.3,4.5,8.5,9.5};
double split1[3]; // arrays if differing sizes
double split2[7];
double split3[2];
size_t start_pos; //position accumulator
size_t cpy_len[SPLIT_CNT] = {3,7,2}; //known array sections
double *split[] = {split1,split2,split3}; //enables looping on arrays of differing sizes
start_pos = 0;
for(int i=0;i<SPLIT_CNT;i++)
{
if(i > 0)start_pos += cpy_len[i-1]; //move the start postition
memcpy(split[i], &source[start_pos], sizeof(double)*cpy_len[i]);
}

return 0;
}

关于c - 如何将数组的内容复制到两个大小不等的较小数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54787392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com