C++ 使用了未初始化的局部变量“j”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19106689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:30:49  来源:igfitidea点击:

uninitialized local variable 'j' used

c++error-handlingvariable-assignment

提问by user2371621

Here is a section of some code I have. Im getting an error uninitialized local variable 'j' used and I dont see it. as far as I can tell it is being used. Can someone please help?

这是我拥有的一些代码的一部分。我收到错误未初始化的局部变量“j”,但我没有看到。据我所知,它正在被使用。有人可以帮忙吗?

float Calculate(Element ElmAry[30], Formula FormAry[30])
{
    int i;
    int j;
    float MoleWT = 0;
    float MoleSum = 0;
    char e1;
    char e2;
    char f1;
    char f2;

    for(i = 0; i < 30; i++) {

        f1 = FormAry[j].Element1;
        f2 = FormAry[j].ElementA;
        e1 = ElmAry[i].eN1;
        e2 = ElmAry[i].eN1;

        if(e1 == f1 && e2 == f2) {
            MoleWT = ElmAry[i].Weight * FormAry[j].Atom;
            MoleSum = MoleSum + MoleWT;
            j++;
        }
    }

return MoleSum;
}

回答by xbonez

You haven't given ja value, hence the uninitialized variableerror.

您没有给出j值,因此出现uninitialized variable错误。

int j;is not the same as assigning ja value of 0.

int j;与赋值j0 不同。

You should do: int j = 0;

你应该做: int j = 0;

回答by nhgrif

The error isn't that jis being used. The error is that jis being used but it isn't being initialized.

错误不是j正在使用。错误是j正在使用但未初始化。

I suggest changing your forloop to:

我建议将您的for循环更改为:

for(i=0, j=0; i < 30; i++, j++)

As I think this is probably what you're actually trying to do...

因为我认为这可能是你真正想要做的......

回答by justhalf

So you use the variable jfirst in the line

所以你j首先在行中使用变量

f1 = FormAry[j].Element1;

But you haven't assigned any value to jpreviously, hence "uninitialized". The previous mention of jwas in your declaration:

但是您之前没有分配任何值j,因此“未初始化”。之前提到的j是在您的声明中:

int j;

You need to assign a value to it, like 0:

您需要为其分配一个值,例如 0:

int j = 0;

That is call "initialization", because if you don't assign any value to a variable, what value should you expect from that variable?

这就是所谓的“初始化”,因为如果你不给一个变量赋值,你应该从那个变量中得到什么值?