【问题标题】:How do I add two same size binary arrays?如何添加两个相同大小的二进制数组?
【发布时间】:2015-10-09 18:09:32
【问题描述】:

在这个函数中,参数first_complement2second_complement2是2个数组,包含2个2的补码的二进制数字。假设两个给定的 2 的补数具有相同的大小。该函数返回一个 int 数组,其中包含 2 给定大小相同的 2 的补数的加法结果的二进制数字。

int* complement2_add(int first_complement2[], int* second_complement2[], int size)
{
    int i;
    int carry = 0;
    int result_array = (int*)malloc(size * sizeof(int));

    for(i = size-1; i>=0; i--)
    {
        result_array[i] = (first_complement2[i] + second_complement2[i] + carry) %2; //it says "Invalid operands to binary % (have 'int *' and int)"
        carry = (first_complement2[i] + second_complement2[i] + carry)/2 ; //as well as "Invalid operands to binary / (have 'int *' and int)"
    }

    result_array[i] = carry; // and here "subscripted value is neither an array nor pointer nor vector
    int j;

    for(j = 0; j < size; j++)
    {
        printf("%d", result_array[j]);
    }
    return result_array;
}

【问题讨论】:

  • 什么是二进制数组?
  • 二进制数组是 int,可以是任意大小,但大小相同且包含二进制值
  • 它们是常规数组,但只有二进制值,所以我试图对这些数组进行二进制加法
  • second_complement2[i] 是一个int *。不知道这是拼写错误、错误还是有意为之,但您需要取消引用或索引它(如果是数组)以将整数值添加到 first_complement2[i]carry
  • 将编译器警告调高至接近最大值。这段代码中至少有两个问题是任何现代编译器都会标记的。

标签: c arrays binary addition


【解决方案1】:

两个问题:

首先,您的函数声明不正确。 second_complement2是一个数组,所以应该声明为int []或者int *

int* complement2_add(int first_complement2[], int second_complement2[], int size)

其次,您对result_array 的声明不正确。因为您正在为数组动态分配空间,所以它应该是int *。另外,不要将malloc 的结果转换为 C:

int *result_array = malloc(size * sizeof(int));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 2020-12-02
    • 2017-03-14
    • 1970-01-01
    • 2012-03-10
    相关资源
    最近更新 更多