2014-05-10 77 views
0

我想讀取文件並將值存儲到結構數組,然後將值傳遞給函數。第一個printf顯示正確的值,但第二個給出所有0.當將值傳遞給函數時,它也全部傳遞0。存儲值,以結構數組值C

input data 
0 1 
0 2 
0 3 
0 4 
0 5 
typedef struct 
{ 
    int brust_time[MAX]; 
    int arrival_time[MAX]; 
}Time; 


int main() 
{ 
    Time *foo; 
    FILE *fr; 
    char str[10]; 
    int x = 0; 
    int m; 

    fr = fopen("read.txt", "rt"); 

    while(fgets(str, 10, fr) != NULL) 
    { 
    x++; 
    foo = (Time *) malloc(sizeof(Time)); 
    sscanf(str, "%d %d", foo[x].arrival_time,foo[x].brust_time); 
    printf("x: %d B:%d\n", *foo[x].arrival_time, *foo[x].brust_time); 
    } 

    for(m = 0; m <x; m++) 
    printf("*****x: %d ******B:%d\n", *foo[m].arrival_time, *foo[m].brust_time); 

    SJF(foo[x].brust_time,foo[x].arrival_time, x); 
    fclose(fr); 

    return 0; 
} 
+0

富被設置爲在每次迭代中一個新的內存範圍。你沒有陣列。你只能得到最後一次運行的最後一個句柄。你可以將它作爲一個鏈表,並將前一個foo賦給next下一個foo的一個屬性。研究鏈接列表。 –

+0

對不起,有太多東西是你的錯誤。開始小得多(只讀一行,不要動態分配任何內容,並確保添加代碼以檢查所有可能失敗的函數(即至少fopen和scanf)的返回值)。最大限度地打開編譯器的警告,並修復所有錯誤和警告(修復,不要隱藏)。只有當該程序以100%的效率運行時,即使您輸入了錯誤的輸出,也應該繼續。確保你理解數組和指針之間的區別。 – Mat

回答

0

也許是這樣的:

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

#define MAX 10 

typedef struct 
    { 
    int brust_time; 
    int arrival_time; 
    }Time; 

int main() 
    { 
    int rCode=0; 
    Time *foo = NULL; 
    FILE *fr = NULL; 
    char str[10]; 
    int x = 0; 
    int m; 

    /* Open the data file in read (text) mode) */ 
    errno=0; 
    fr = fopen("read.txt", "rt"); 
    if(NULL == fr) 
     { 
     rCode=errno; 
     fprintf(stderr, "fopen() failed. errno[%d]\n", errno); 
     goto CLEANUP; 
     } 

    /* Allocate an array of 'Time' structures large enough to hold all the data. */ 
    foo = malloc(MAX * sizeof(Time)); 
    if(NULL == foo) 
     { 
     rCode=ENOMEM; 
     fprintf(stderr, "malloc() failed.\n"); 
     goto CLEANUP; 
     } 

    /* Read, parse, and store each line's data in the array of structures. */ 
    while(x<MAX) 
     { 
     /* Read a line. */ 
     errno=0; 
     if(NULL == fgets(str, 10, fr)) 
     { 
     if(feof(fr)) 
      break; 

     rCode=errno; 
     fprintf(stderr, "fgets() failed. errno[%d]\n", errno); 
     goto CLEANUP; 
     } 

     /* Parse & store */ 
     sscanf(str, "%d %d", &foo[x].arrival_time, &foo[x].brust_time); 
     ++x; 
     } 

    /* Generate report. */ 
    for(m = 0; m < x; m++) 
     printf("*****x: %d ******B:%d\n", foo[m].arrival_time, foo[m].brust_time); 

/* Restore system. */ 
CLEANUP: 

    /* Free Time structure array. */ 
    if(foo) 
     free(foo); 

    /* Close the file. */ 
    if(fr) 
     fclose(fr); 

    return(rCode); 
    }