我编写了一个非常基本的程序来从文件中读取非常大的数字并计算连续数字的最大乘积。为了提醒一些 C 基础知识,我决定用 C 语言编写它。在我装有 Linux 的家用机器上,它运行得非常顺利。在 Visual Studio 2013 Express 上,它会抛出一些错误并挂起(可能与内存管理有关)。你知道发生了什么事吗?
int ch, i = 0, *ptr, count = 0, j;
FILE *f;
int *arr;
//Opening file in read mode
f = fopen("test.txt", "r");
if (f == NULL) {
printf("Error");
return 0;
}
//intial allocation
arr = malloc((count + 1) * sizeof(int));
ptr = arr;
while ((ch = fgetc(f)) != EOF) {
if (ch == 10) {
continue; //exclude new line character
}
*ptr = (ch - 48); //populating array
ptr++;
count++;
arr = realloc(arr, (count + 1) * sizeof(int));
}
int p0 = 1;
int maxp = 1;
//calculating largest product of five consecutive digits
for (i = 0; i < count - 5; i++) {
p0 = 1;
for (j = 0; j < 5; j++) {
p0 *= arr[i + j];
}
if (maxp < p0) {
maxp = p0;
}
}
printf("%d", maxp);
return EXIT_SUCCESS;
最佳答案
在 while 循环中,您每次都会重新分配缓冲区(顺便说一句,这是完全低效的,但那是另一个故事了)。但是您继续使用 ptr 指针,该指针指向在 while 循环之前由 malloc 分配的缓冲区。 realloc 函数可能返回与先前分配的指针的地址相同的地址,在这种情况下您的程序似乎可以工作。但是,如果返回的地址不同,则ptr
不再有效,您的程序将无法运行,甚至可能崩溃。
这应该可行(尽管效率仍然很低):
while ((ch = fgetc(f)) != EOF) {
if (ch == 10) {
continue; //exclude new line character
}
arr[count++] = (ch - 48); //populating array
arr = realloc(arr, (count + 1) * sizeof(int));
}
关于c - 同样的C程序在Windows上无法运行,但在Linux上却可以完美运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22499042/