Anik Shahriar Anik Shahriar - 12 days ago 5
C Question

Subscripted value nor array nor pointer nor vector

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?

Answer

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();

}