嗨,我非常喜欢编码,我最近打了一个砖墙
这个程序有一个分段错误调试,我认为它与为缓冲区数组或输入文件分配空间有关,因为那些在搜索答案时一直作为解决方案弹出。 如果你知道我做错了什么,如果你告诉我而不是给我解决方案,我将不胜感激。我完全失去了如何为任何东西分配内存,所以如果有人解释如何在代码的上下文中分配内存,那将会很棒。
应该读取这样结构的文件
2
3 4
3 4
其中2 =正在下载的文件数量,3 =文件的Kb / s(每行代表一个文件),4 =完成前剩余的时间。该程序应该输出一个文件,该文件具有下载所有内容所需的时间(当文件完成速度升级到其他人时请注意)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
FILE *in = fopen("download.in", "r");
FILE *out = fopen("download.out", "w");
int i, n, j, a, k, o;
char buffer[100];
fgets(buffer, 10, in);
sscanf(buffer, "%d", &n);
int tn[n];
int xn[n];
i = 0;
while (i < n) {
fgets(buffer, 100, in);
sscanf(buffer, "%d %d", &tn[i], &xn[i]);
++i;
}
for (i = 0; i < n; ++i){
for (j = i + 1; j < n; ++j){
if (tn[i] > tn[j]){
a = tn[i];
tn[i] = tn[j];
tn[j] = a;
a = xn[i];
xn[i] = xn[j];
xn[j] = a;
}
}
}
i = 1;
float b ;
k = 0;
o = 1;
while(o < n){
if(xn[o] == xn[o - 1]){
k = tn[o] + tn[o - 1]
;
}
else{
b = (tn[o] * xn[o]) / (tn[o] + tn[o - 1] + k);
k = 0;
}
++o;
}
fprintf( out, "%f", b );
fclose(in); fclose(out);
return 0;
}
我知道它给出的答案并不准确但我想先解决分段错误然后处理
gdb r然后gdb bt返回此
(gdb) r
Program received signal SIGSEGV, Segmentation fault.
_IO_fgets (buf=0x7fffffffeb30 "", n=10, fp=0x7fffffffeac0) at iofgets.c:50
50 iofgets.c: No such file or directory.
(gdb) bt
#0 _IO_fgets (buf=0x7fffffffeb30 "", n=10, fp=0x7fffffffeac0) at iofgets.c:50
#1 0x0000000000400766 in main () at main.c:11
codeblocks说代码没问题,而我试图给出的网站也说有分段错误。
答案 0 :(得分:0)
以下是修复了segfault的代码。我必须(1)指定绝对路径和(2)将循环更改为for循环。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
FILE *in = fopen("/home/developer/CLionProjects/untitled4/download.in", "r");
FILE *out = fopen("/home/developer/CLionProjects/untitled4/download.out", "w");
int i, n, j, a, k, o;
char buffer[100];
fgets(buffer, 10, in);
sscanf(buffer, "%d", &n);
int tn[n];
int xn[n];
for (i = 0; i < n; i++) {
if (!fgets(buffer, 100, in)) break;
if (sscanf(buffer, "%d %d", &tn[i], &xn[i]) < 2) break;
}
for (i = 0; i < n; ++i) {
for (j = i + 1; j < n; ++j) {
if (tn[i] > tn[j]) {
a = tn[i];
tn[i] = tn[j];
tn[j] = a;
a = xn[i];
xn[i] = xn[j];
xn[j] = a;
}
}
}
i = 1;
float b;
k = 0;
o = 1;
while (o < n) {
if (xn[o] == xn[o - 1]) {
k = tn[o] + tn[o - 1];
fprintf(out, "Some number: %d\n", k);
} else {
b = (tn[o] * xn[o]) / (tn[o] + tn[o - 1] + k);
k = 0;
fprintf(out, "Some number: %d\n", k);
}
++o;
}
fclose(in);
const char *text = "Write this to the file";
fprintf(out, "Some text: %s\n", text);
fclose(out);
int c;
FILE *file;
file = fopen("/home/developer/CLionProjects/untitled4/download.out", "r");
if (file) {
while ((c = getc(file)) != EOF)
putchar(c);
fclose(file);
}
return 0;
}