我尝试使用 gcc 编译并 运行 以下冒泡排序程序,但它显示错误

I tried to compile and run the following bubble sort program using the gcc but it shows the error

{

int *v;
int i=0; 
int n;
int j=0;
int aux=0;
File *fp;

fp = fopen("Inteiros.txt", "r"); /*opening a file and read it*/

if(fp == NULL)

    printf("Erro, ficheiro nao encontrado!\n");/*portuguese sentence*/

else

    while(!feof(fp))

    {
        fscanf(fp, "%d", &v[i]);
        i++;
    }

    for(i=1; i<n; i++)
    {   
        for(j=0; j< n-i-1; j++)
        {
            if(v[j] > v[j+1])
            {   
                aux = v[j];
                v[j] = v[j+1];
                v[j+1] = aux;
            }
        }   
    }

而不是 "segmentation fault" 错误,我不知道为什么。 我知道这是一段我无法访问的内存,但我不知道错误在哪里。

您可能会遇到段错误,因为您没有为指针 int *v 分配任何内存,然后您尝试将值分配给它,就像它是一个数组一样。此外 int n; 从未初始化,因此您进入了未定义的行为。 File 也不是一种类型,除非你自己制作了你没有展示的类型,应该是 FILE.

尝试这样的事情:

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

#define MAX_NUMS  1024

int main()
{

   int *v;
   int i=0, j=0, aux=0, n = 0;
   FILE *fp;

   fp = fopen("Inteiros.txt", "r");

   if(fp == NULL) {
      printf("Erro, ficheiro nao encontrado!\n");
      return 1;
   }
   else {
      //allocate memory for v
      if ((v = malloc(sizeof (int) * MAX_NUMS)) == NULL) {
         printf("Error in malloc\n"); 
         return 1;
      }

      while(!feof(fp)) {
         fscanf(fp, "%d", &v[i]);
         i++;
      }
      //number of lines read
      n = i;
      for(i = 0; i < n; i++) {
         for(j = 0; j < n-i-1; j++) {
            if(v[j] > v[j+1]) {
               aux = v[j];
               v[j] = v[j+1];
               v[j+1] = aux;
            }
         }
      }
      for (i = 0; i < MAX_NUMS; i++)
         printf("v[%d] is %d\n", i, v[i]);
   }
   return 0;
}