c - 如何添加两个相同大小的二进制数组?

标签 c arrays binary addition

在此函数中,参数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;
}

最佳答案

两个问题:

首先,您的函数声明不正确。 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));

关于c - 如何添加两个相同大小的二进制数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33044667/

相关文章:

javascript - 从数组内容设置 div id

c - 无法初始化二维数组

machine-learning - 二元分类准确率低于 50%

c - 从C中的二进制文件读取一行 float

c++ - 两条相似线路的 CPU 时间差异

c++ - 如何检查 LIB 导入库是否完全匹配其 DLL?

java - JNA:指向字符的指针**

c - 不合逻辑的 C6001 警告 : Using uninitialized memory warning in C with Visual Studio

python - 如何从 python 中的原始输入创建 numpy 数组?

c# - 从 Process.StandardOutput 捕获二进制输出