嗨,所以我的编码是新的,我最近遇到了一个砖砌
此程序具有分段故障调试,我认为这与为缓冲区数组或输入文件分配空间有关,因为在我搜索答案时,这些程序一直弹出为解决方案。如果您知道我做错了什么,如果您告诉我而不是给我解决方案,我会很感激。我也完全失去了如何将内存分配给任何事物,因此,如果有人解释了如何在上下文中分配内存,那将是很棒的。
应该读取像这样构建的文件
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说代码还可以,我试图给出的网站说有一个分割的故障。
这是带有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: %dn", k);
} else {
b = (tn[o] * xn[o]) / (tn[o] + tn[o - 1] + k);
k = 0;
fprintf(out, "Some number: %dn", k);
}
++o;
}
fclose(in);
const char *text = "Write this to the file";
fprintf(out, "Some text: %sn", 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;
}