【问题标题】:merging arrays that are pointers into one (of a different size), in C在C中将作为指针的数组合并到一个(不同大小的)中
【发布时间】:2020-11-27 07:54:08
【问题描述】:

编辑:

int *combined;
combined = malloc(24 * sizeof(int));

for (int i = 0; i < 24; i++) {
   combined[i] = 0;
}

decToBinary(theValue, &combined);
decToBinary(otherValue, &combined + 4);

int *decToBinary(int n, int *buff) {
    int i = 0;
    while (n > 0) {
        buff[i] = n % 2;
        n = n / 2;
        i++;
    }
}

自从我完成 C 语言以来,我一直在玩 Arduino 代码。我很好奇是否可以将不同大小的数组合并为一个大数组。

数组是一堆 4 个元素的数组,我想将其中的 6 个合并成一个 24 个元素的数组?

我已经走到这一步了:

  int *someVal;  
  someVal = decToBinary(2); //returns my 4 element array

  //do the above to a different int* someVal1 6 other times...
  //then...
  int *combined; //24 'lights'
  combined = malloc(24 * sizeof(int));

memcpy吗? (查看文档似乎无法分段使用 memcopy 将其“打包”到数组中)。它们必须是相同的尺寸吗?我想要这样的结果:

[0,1,0,0]
[1,1,0,0]
[1,0,0,1]
[1,0,1,0]
[0,1,1,0]
[0,0,0,1]

变成:

[0,1,0,0,1,1,0,0,1,0,0,1,1,0,1,0,0,1,1,0,0,0,0,1]

我的意思是我可以通过在每个数组中迭代 6 次并使用外部计数器将大数组的每个元素设置在上面来做到这一点......只是在寻找更优雅的东西。

【问题讨论】:

  • 你控制decToBinary接口和实现吗?为什么不修改或创建一个将结果写入调用者提供的缓冲区,而不是在堆上分配临时数组?
  • 如果可行,请编写一个 decToBinary 的版本,它本机接受一个 4 元素数组作为参数:即dec2BinaryAr(int val, int *ar),然后在目标阵列的六个位置上发射。 IE。 combinedcombined+4 等。简而言之,将您的转换直接转换为您的组合数组。
  • 这些都是很棒的想法(相似)。再次深入 C 是一种乐趣。我确实将 dec 控制为二进制!所以我就这样做了,但现在我忘记了是否必须返回缓冲区或以某种方式使用地址....哇。确实,如果你不使用它,你就会失去它。将版本放在OP的编辑中
  • 你的decToBinary 函数没有返回任何东西。
  • 这是真的,我不确定在 C 语言中如何使它按地址而不是按值工作,我以为我用 & 正确添加了它,但我认为我把它们搞砸了

标签: arrays c pointers


【解决方案1】:

在这个例子中,我将 6 个 4 个 int 数组分配给相同的数字 (1, 2, 3...),并将它们存储在一个由 6 个指针 (someVals) 组成的数组中。然后我将 6 个数组合并为一个 24 个元素的数组(合并)并打印结果:

int * decToBinary(int n) {
    int *ar = malloc(sizeof(int) * 4);
    for (char i=0; i<4; i++) ar[i] = n;
    return ar;
}

int main()
{
    int* someVals[6] = {0};  
    for(char i=0; i<6; i++) {
        someVals[i] = decToBinary(i + 1);
    }
    int* combined;
    combined = malloc(24*sizeof(int));
    int * ptr = combined;
    for(char i=0; i<6; i++) {
         memcpy(ptr, someVals[i], sizeof(int) * 4);
         ptr += 4;
    }
    for (char i=0; i<24; i++) printf("%d ", combined[i]); //=> 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6 6 6 
    
    for (char i=0; i<6; i++) free(someVals[i]);
    free(combined);
    return 0;
}

【讨论】:

    猜你喜欢
    • 2016-09-16
    • 2015-12-09
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多