0
votes

This is my program to convert a binary to a decimal value.

#include <stdio.h>
#include <string.h>
#include <math.h>

void con(){

    unsigned long long int dec = 0, bin;
    int i;

    printf ("\n Binary : ");
    scanf("%lld",&bin);



    for (i = strlen(bin) - 1; i <= 0; --i){    // Warning in here

       dec = dec + (bin[i] * pow (2, i));   // Error in here

    }

    printf(" Decimal : %lld",dec);

    con();

}

int main(){

    con();
    return 0;
}

When i compile the code, this error shows up ," Subscripted value is neither array nor pointer nor vector". And this warning also ," Passing argument 1 of strlen makes pointer from integer without a cast".

Why am i getting these and how can i fix them?

2
bin is unsigned long long int, not a pointer or an array... - StoryTeller - Unslander Monica
@StoryTeller So i should use it as an array ? - Anik Shahriar
You should declare it as an array, if you intend to use it as one... - StoryTeller - Unslander Monica

2 Answers

2
votes

There are a number of problems with your code.

Most important is the variable bin. You probably want it to be a string like "1001001001" but you define it as unsigned long long int. Instead you should do:

char bin[100];
scanf("%s", bin);   // Note: Not recommended! Use fgets instead.

Here scanf is not recommended as the user may overflow your buffer. Please use fgets instead.

As suggested by @MayurK: If you want to use scanf then at least do:

scanf("%99s", bin);

to prevent buffer from overflow.

Then this part:

dec = dec + (bin[i] * pow (2, i));

is wrong as bin[i] is not a number but a char.

You could do:

dec = 2 * dec + (bin[i] - '0');  // Note: No error checks which is bad

It will work as long as the user only inputs 0 and 1. In real code you should check that the user actually did so.

Finally you should not call con at the end of the function as it will give an endless loop. So delete that call:

    printf(" Decimal : %lld",dec);

    // DELETE THIS con();

}
1
votes
dec = dec + (bin[i] * pow (2, i));  //bin is a numeric type

In this line you are trying to use a variable of unsigned long long type as array. Every numeric type is taken as a full value, you can't use array indexing to access separate digits. If you want to use it as a array use a char* or character array.

And you are also passing a unsigned long long to strlen(const char * str) function.