更改的变量名称会导致运行时错

时间:2017-10-31 01:52:23

标签: c arrays loops runtime overflow

我真的很困惑,为什么第二个例子导致运行时错误,只有差异是变量名称。有人可以解释为什么会这样吗?

int main (void)
{
    long long ccNumber;
    int ccLength;
    printf("Enter Credit Card Number: ");
    ccNumber = get_long_long();
    ccLength = (int)log10(ccNumber) + 1;
    if (ccLength != 13 && ccLength != 15 && ccLength != 16)
        printf("Invalid Card Number.\n");

    int array[ccLength];
    long long copyCcNumber = ccNumber;
    int loopCounter = 0;

    while (copyCcNumber != 0)
    {
        array[ccLength - 1 - loopCounter] = copyCcNumber % 10;
        copyCcNumber = copyCcNumber / 10;
        loopCounter++;
    }

:此

    int numberArray2[ccLength/2];
    int k = 2;
    int l = 0;

    while ((ccLength - k) > -1)
    {
        numberArray2[l] = 2 * array[ccLength - k];
        k = k + 2;
    l++;
    }
    return 0;
}

VS

    int array2[ccLength/2];
    int everyOtherDigit = 2;
    int loopCounter2 = 0;

    while ((ccLength - loopCounter2) > -1)
    {
        array2[loopCounter2] = 2 * array[ccLength - everyOtherDigit];
        everyOtherDigit = everyOtherDigit + 2;
        loopCounter2++;
    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

好吧,你有一个简单的副本&粘贴错误:在while循环内部,您没有将array重命名为array2,而while ((ccLength - loopCounter2) > -1)应该是while ((ccLength - everyOtherDigit ) > -1)

int array2[ccLength/2];
int everyOtherDigit = 2;
int loopCounter2 = 0;

while ((ccLength - everyOtherDigit) > -1)
{
    array2[loopCounter2] = 2 * array2[ccLength - everyOtherDigit];
    everyOtherDigit = everyOtherDigit + 2;
    loopCounter2++;
}