Two's complement in C++ - invalid types 'int[int]' for array subscript

542 views Asked by At

I'm trying to implement some sort of a two's complement algorithm in C++ and so far I think my logic is correct. However, I get the following error when I run it invalid types 'int[int]' for array subscript

#include <iostream>
#include <stdio.h>
using namespace std;

int main(){

    int a[4] = {0, 2, 3, 5};
    int b[4] = {9, 7, 8 ,4};

    int sum = 0;
    int transmit = 0;
    int c{0};

    for (int k=3;k>0;k--){
        sum = a[k]+b[k]+transmit;
        c[k+1]=sum%10;
        transmit=sum/10;
    }

    c[0] = transmit;
    return 0;
}
2

There are 2 answers

9
LewisCheng-MSFT On BEST ANSWER

I guess your purpose is to do plus operation of two int arrays? A little explanation: you have to declare five units for 'c' as there may be one additional carrier (you called transmit)

#include <iostream>
#include <stdio.h>
using namespace std;

int main(){

    int a[4] = {0, 2, 3, 5};
    int b[4] = {9, 7, 8 ,4};

    int sum = 0;
    int transmit = 0;
    int c[5] = {0};

    for (int k=3;k>0;k--){
        sum = a[k]+b[k]+transmit;
        c[k+1]=sum%10;
        transmit=sum/10;
    }

    c[0] = transmit;
    return 0;
}

With this format: array of decimal integers, they are somewhat hard to be converted to a binary directly. But I can still try to give out a solution:

// first convert to an unsigned int
unsigned int result = 0;
for (int k = 0; k < 5; ++k) {
    result *= 10;
    result += c[k];
}

// then convert to binary
char binary[32]; // 32bit should be enough
int len = 0;
while (result > 0) {
    binary[len++] = (result % 2) + '0';
    result /= 2;
}

// finally print binary
for (int k = len - 1; k >= 0; --k) {
    printf("%c", binary[k]);
}

The full program:

#include <iostream>
#include <stdio.h>
using namespace std;

int main(){

    int a[4] = {0, 2, 3, 5};
    int b[4] = {9, 7, 8 ,4};

    int sum = 0;
    int transmit = 0;
    int c[5] = {0};

    for (int k=3;k>0;k--){
        sum = a[k]+b[k]+transmit;
        c[k+1]=sum%10;
        transmit=sum/10;
    }

    c[0] = transmit;

    // first convert to an unsigned int
    unsigned int result = 0;
    for (int k = 0; k < 5; ++k) {
        result *= 10;
        result += c[k];
    }

    // then convert to binary
    char binary[32]; // 32bit should be enough
    int len = 0;
    while (result > 0) {
        binary[len++] = (result % 2) + '0';
        result /= 2;
    }

    // finally print binary
    for (int k = len - 1; k >= 0; --k) {
        printf("%c", binary[k]);
    }

    printf("\n");

    return 0;
}
2
sjdowling On

c is of type int

int c{0};

And you are trying to deference it as if it was an array:

c[k+1]=sum%10;

You cannot legally dereference an int.