gpt4 book ai didi

c - 尝试运行此程序时出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 06:48:27 24 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>
#include "vettore.h"

int main(int argc, char *argv[]){
if(argc != 5)
printf("Incorrect parameters number\n");
else{
int n = atoi(argv[1]);
int *a = (int*) calloc(n, sizeof(int));
if(a == NULL)
printf("Unsufficient memory\n");
else{
finput_array(argv[2], a, n);
bubblesort(a, n);
foutput_array(argv[4], a, n);
int *oracle = (int*) calloc(n, sizeof(int));
finput_array(argv[3], oracle, n);

if(compare_array(a, oracle, n))
printf("PASS\n");
else
printf("FAIL\n");
}
}
}

我这样运行程序:./test_ordina_array.exe 12 TC4_input.txt TC4_oracle.txt TC4_output.txt 但它给我段错误。

“TC4_output.txt”是由程序创建的,而其他两个文件已经存在。

这是使用的函数:

    void bubblesort(int a[], int n){
int i, j;
for(i = 0 ; i < n - 1; i++)
{
for(j = 0 ; j < n - i - 1; j++)
{
if (a[j] > a[j+1]) /* For decreasing order use < */
{
swap(&a[j], &a[j+1]);
}
}
}
}

void finput_array(char *file_name, int a[], int *n){
FILE *fd = fopen(file_name, "r");
if(fd == NULL)
printf("Errore in apertura del file %s\n", file_name);
else{
int i = 0;
fscanf(fd, "%d", &a[i]);
while(i<*n && !feof(fd)){
i++;
fscanf(fd, "%d", &a[i]);
}
fclose(fd);
if(i<*n)
*n = i;
}
}

void foutput_array(char *file_name, int a[], int n){
int i;
FILE *fd;

fd = fopen(file_name, "w");
if(fd == NULL)
printf("Errore in apertura del file %s\n", file_name);
else{
for(i=0; i<n; i++)
fprintf(fd, "%d\n", a[i]);
fclose(fd);
}
}

int compare_array(int a[], int b[], int n){
int i=0;

while(i<n && a[i] == b[i])
i++;

return (i==n) ? 1 : 0;
}

它们包含在“vettore.c”中,“vettore.h”包含它们的原型(prototype)。

程序必须按升序排列第一个 txt 文件中包含的元素,并将它们写入输出文件。

最佳答案

使用 finput_array 时遇到问题

finput_array(argv[2], a, n);

请替换为

finput_array(argv[2], a, &n);

关于c - 尝试运行此程序时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54768281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com