在此函数中,参数first_complement2
和second_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/