Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C:当数组增长到超过6个元素时,会出现堆栈溢出_C - Fatal编程技术网

C:当数组增长到超过6个元素时,会出现堆栈溢出

C:当数组增长到超过6个元素时,会出现堆栈溢出,c,C,当运行下面的代码时,我收到一条堆栈溢出错误消息,但仅当输入的数字超过6位时。我认为代码相当简单,到目前为止,我所能找到的帮助都是关于“内存分配”的答案,我还没有任何概念 int main(void) { printf("Please enter card number for check: \n"); long long credit_card = GetLongLong(); int card_length = log10(credit_card)+1;

当运行下面的代码时,我收到一条堆栈溢出错误消息,但仅当输入的数字超过6位时。我认为代码相当简单,到目前为止,我所能找到的帮助都是关于“内存分配”的答案,我还没有任何概念

int main(void)
{   
    printf("Please enter card number for check: \n");
    long long credit_card = GetLongLong();
    int card_length = log10(credit_card)+1;
    int cred_array[card_length];
    long long dec = 1;
    int i;

    printf("credit_card: %lli\n",credit_card);
    printf("card_length: %i\n",card_length);
    for (i = (card_length-1); i>-1; i--)
    {
        cred_array[i]=(credit_card/dec)%10;
        dec *=10;
    }
    int luhn_array[(credit_card-(credit_card % 2)) / 2][2];
    int j;
    int n = 0;
    for(j = card_length-2; j >= 0; j-=2)
    {
        luhn_array[n][0]=cred_array[j]*2%10;
        luhn_array[n][1]=cred_array[j]*2/10;
        n++;
    }
} 

如果您输入6位或更多数字的信用卡,如
987654
,则此行:

int luhn_array[(credit_card-(credit_card % 2)) / 2][2];
变成:

int luhn_array[987654 - 0/2][2];
或者只是
int luhn_数组[987654][2]

这实际上是在试图分配:

987,654 * 2 * 4-bytes-per-int = 7,901,232 bytes on the stack!
那还差8场呢!你的内存大约是1MB
怪不得你满溢


编辑:哎呀,我把最初的数学搞砸了。比我想象的还要糟糕!答案已修改。

看起来像
int-luhn\u数组[-1]
我的问题是:
int-luhn\u数组[(信用卡-(信用卡%2))/2][2]
您正在创建一个巨大的数组。它似乎也是多余的…如果
信用卡
是偶数,减去2的模没有任何作用,如果
信用卡
是奇数,您将通过整数除法得到相同的效果下次请包含整个源文件,包括任何
\include
指令。请注意,
log10
是一个浮点函数,容易出现舍入错误,因此不一定是计算整数位数的好方法。我不知道为什么我没有在头脑中把它拼凑起来。我应该参考卡的长度。现在看来是个大错误。谢谢大家!