我以一种非常乏味的方式做这个课程,但明天就要到了,所以我现在必须坚持这种方式,因为我没有太多时间去弄清楚另一个。这个代码做了什么它需要一个10位数字并将其分成10位数,检查从1到这个数字的每种可能性,如果10位数之和等于37,如果是,它会增加一个计数器给出总数数字加起来的数字的数量是37。问题就是这么大的数字我觉得内存分配有问题,而这种情况发生了,当我在macOS终端上运行时,它给出了错误“Killed:9”(之后)一段时间的c) 这是我的源代码(In C语言):
#include<stdio.h>
#include<stdlib.h>
int main()
{
long long *counter = malloc(9999999999 * sizeof(*counter)); // size of array should be up to 9999999999
long long counter2 = 1; // long long because counter 2 goes up to 10 digits , MAX 9999999999
int FirstDigit, secondDigit ,ThirdDigit , fourthdigit, fifthdigit , sixthdigit,seventhdigit,eightdigit,ninthdigit,tenthdigit ;
unsigned long z2 , z3 ,c , z1 , z4 , z5,z6 ,z7; // max 9 digits
unsigned long count = 0; // max 9 digits
for (long long i = 1 ; i<9999999999 ; i++)
{
counter[i] = counter2; // appends number to array
counter2 += 1; // increments counter for next append
FirstDigit = counter[i] / 1000000000;
z1= counter[i] / 100000000;
secondDigit = z1 % 10;
c = counter[i] / 10000000;
ThirdDigit = c % 10 ; // a holds 3rd digit
z3 = counter[i] / 1000000;
fourthdigit = z3 % 10; // d holds 2nd digit
z2 = counter[i] /100000;
fifthdigit = z2 % 10;
z4 = counter[i] / 10000;
sixthdigit = z4 % 10;
z5 = counter[i] / 1000;
seventhdigit = z5 % 10;
z6 = counter[i] / 100;
eightdigit = z6 % 10;
z7 = counter[i] / 10;
ninthdigit = z7 % 10;
tenthdigit = counter[i] % 10;
if( (FirstDigit + secondDigit + ThirdDigit + fourthdigit + fifthdigit + sixthdigit + seventhdigit +eightdigit + ninthdigit + tenthdigit) == 37 )
{
count+= 1;
}
}
printf("%lu\n", count );
}
答案 0 :(得分:1)
在此之后
long long *counter = malloc(9999999999 * sizeof(*counter));
把
printf("Address returned by malloc: %p\n", (void*) counter);
您会看到它返回0,因为您的系统无法分配那么多内存,现在当您尝试写入该地址时,您将获得段错误。请务必查看malloc
的返回代码。
答案 1 :(得分:1)
问题是为您的应用程序保留几千兆字节的内存可能会失败,表明counter
将为NULL
。您可以通过编写if(counter==NULL) { printf("could not allocate memory."); return 1; }
轻松查看此内容。如果不对此进行检查,则将访问不允许访问的内存,从而产生未定义的行为,通常会产生段错误。
BTW:仅计算数字的总和,您不需要实际存储要在内存中检查的所有数字。因此不需要完整的counter
- 数组。移除malloc
并将counter[i]
替换为循环中的i
:
for (long long i = 1 ; i<9999999999 ; i++)
{
FirstDigit = i / 1000000000;
z1= i / 100000000;
secondDigit = z1 % 10;
...
}