Anik Shahriar
Anik Shahriar

Reputation: 151

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?

Upvotes: 0

Views: 64

Answers (2)

4386427
4386427

Reputation: 44329

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

}

Upvotes: 2

abhinav
abhinav

Reputation: 31

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.

Upvotes: 1

Related Questions