gpt4 book ai didi

C - 段错误

转载 作者:太空宇宙 更新时间:2023-11-04 08:36:56 25 4
gpt4 key购买 nike

当我使用包含 5 个数字的 txt 文件运行程序时,我不断收到段错误。第一个数字是 5(数组的大小),然后是 0 1 2 3 4 它在我 gcc -c *.c 时编译得很好。

主文件

#include <stdio.h>
#include <stdlib.h>
#include "my.h"
int main(int argc, char *argv[])
{
char* file = argv[1];
int n;
int* a;
int i,j;

FILE *fp;
fp = fopen(file, "r"); // open file

fscanf(fp, "%d", &n); //scans for the first value for n

a = calloc(n, sizeof (int));
int num;

for (i =0; i<n - 1; i++) //stores and reads value
{
fscanf(fp, "%d", &num);
a[i] = num;
}
fclose(fp);
int* b;
b = f(a, n);
displayValue(b);

return 0;
}

函数

#include <stdio.h>
#include <stdlib.h>
#include "my.h"
int* f(int* a, int n)
{

//odd-even sort
int h,j, c;
for ( h = 0; h < n - 1; h++)
{
if(a[h]%2==0)
{
if (a[h] > a[h + 1])
{
int temp = a[h];
a[h] = a[h +1];
a[h + 1] = temp;
}
}
}

for (j = 0; j < n - 1; j++)
{
if(a[j]%2!=0)
if (a[j] > a[j + 1])
{
int temp = a[j];
a[j] = a[j +1];
a[j + 1] = temp;
}
}
return a;
}

void displayValue(int* b)
{
int index = 0;
while (0 == 0)
{
printf("Enter the index: ");
scanf("%d", &index);
if (index == -1)
exit(0);
else
printf("%s", &b[index]);
}
}

标题

int main(int argc, char *argv[]);
int* my(int* a, int n);
void displayValue(int* b);

最佳答案

C 很危险。任何可能出错的事情都会出错。

经常检查函数调用的返回值,并处理可能的失败。

每个标准库函数调用都有一个 man页面(如果找不到它,请使用 man -a <function> )。 man页面记录了可能的返回值及其含义。 man是你炸的,习惯研究它;这是一种宝贵的资源。

当心导致“未定义行为”的情况。

关于C - 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25829400/

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