in visual c++, warning comes but program doesnt runs furthers, is there any way to igonre it?

137 views Asked by At

I have written some code, here is a snippet of it is:

int num[8],n=0;
for (n = 0; n<8; n++)
{
    char temp = binnum[n];
    num[n] = atoi(&temp);
    cout << num[n];
}

It doesn't gives any error, but I do get a warning. When I run it on C++, it gives Run Time Check Failure - The variable n is being used without being initialized. After that, it doesn't run any further and the program closes. Is there any way to ignore this error? Because if I initialize n, it gives the wrong answer. For example, if answer is 101011, it will give 10101100, which is wrong.

6

There are 6 answers

0
UncleBens On

Your main problem (after all the edits) is that atoi takes a null-terminated char array (C-style string). The address of a single char variable does not make a C-style string.

To convert a single character in range ['0'...'9'] to a corresponding number use:

number[i] = temp - '0';

possibly having checked that temp contains a digit character.

4
anthares On

Give a value to your vairable n before using it int number [8], n=0 for example. Otherwise, it is "not defined behavior" what is the value of n and how many iterations you will do in your cycle.

Also, As it is written your loop will go forever since you never change the value of n ...

2
alanp On

You are using n before it is assigned a value. You need to ensure that n is initialized (to 0, maybe) before you begin to reference it in your code. You do not want to ignore this error.

Try something like this:

const int count = 8;
int number[count];
    for (int i=0; i < count; i++)
    {
        char temp = binnum[i];
        number[i] = atoi(&temp);
        cout << number[i];
    }
2
Itay Karo On

what? you never assign any value to n.
and even if you will for example do int number[8],n=0; you never change n's value you you will end up with an infinite loop.

3
karlphillip On

Initialize n as @anthares pointed out and increment it at the end of the loop so your loop actually works.

int number[8];
int n = 0;
do
{
    char temp = binnum[n];
    number[n] = atoi(&temp);
    cout << number[n];
    n++;
} while (n<8);
0
foraidt On

You should really initialize n (and also increment it, for that matter).
You are probably running a debug build of your application. In this case, the variable is probably always initialized with the same value. This is why you see the result you expect. It seems to behave correct purely by accident.
As soon as your application is built in release mode, n may have a different value each time the program is run and thus the output will be unpredictable. This is what happens when you have undefined behavior in your program.