C - 段错误

标签 c segmentation-fault

当我使用包含 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/

相关文章:

c - C 是否在右括号之前销毁返回变量?

c - getcwd 是否有任何替代 API 来获取进程的工作目录

iphone - 用于 H.323 音频的开源 Objective C(或 C/C++)库?

c - 从共享内存读取段错误

c - 功能结束时出现段错误

c - 正确使用strcmp函数?

c - 什么是静态 int ** volatile ptr?

c - 程序收到信号SIGSEGV、段错误、链表程序

c - 尝试检索值时,将指针传递给函数会导致段错误

c - 字符数组的段错误