2014-09-27 23 views
-1

我正在處理文件,並在編譯完成後給我一個分段錯誤錯誤。 我試圖打開一個文件並將其保存在一個向量中。另外我想用dinamic內存來分配它。C程序。文件。

#include "stdio.h" 
#include "stdlib.h" 

main(){ 

    int n,v[n],i,c,cant; 


    FILE*archivo; 

    archivo = fopen("vectores.dat","wb"); 
    if(archivo == NULL) 
    { 
     printf("Error while opening"); 
     exit(1); 
    } 


    printf("write the number of integers you want to save in the file"); 
    scanf("%d",&cant); 


    for(i=0;i<cant;i++){ 

    printf("write the number in the position: %d",i+1); 
    scanf("%d",v[i]); 
    } 


    c= fwrite(v,sizeof(int),n,archivo); 
    if(c<1){ 

    printf("Error while writing"); 
    exit(1); 
    } 

} 

回答

2

這裏是一個問題:

int n,v[n],... 

首先聲明變量n,但你不初始化它,然後你聲明v作爲n整數數組。與此問題是,因爲n未初始化它的值是不確定,並且您有undefined behavior

您以後再次使用n,仍然沒有初始化。

如果你的程序在任何地方都有未定義的行爲,它是不合格的,沒有任何代碼可以被信任。

+0

你沒有意識到程序員有一個心理編譯器:-) – 2014-09-27 09:04:39

+0

@EdHeal太棒了!我可以在哪裏下載它?幾十年來一直想要其中之一。一個精神連接器會更好,沒有更多的makefiles :) – 2014-09-27 09:14:09

+0

@MartinJames - makefiles - 這是舊的skool – 2014-09-27 09:16:36