2013-04-29 65 views
0

我正在開發一個項目,其中需要從文本文件讀取CSV行到我的程序中。我被給了一個代碼框架,並要求填寫功能。我有一個結構,它包含一個變量,用於我將要接收的每種類型的值,但是我的char數組導致了段錯誤。 這是我的代碼摘錄。 沒有exerpt是給定代碼的一部分,這是我的全部: 由於get timestamp空間內的代碼,我的錯誤是分段錯誤(核心轉儲)。 我的測試文件只包含一個線, 5,10時00分10秒,1,997在解析C中的CSV行時發生Seg錯誤

/* 
* YOUR CODE GOES HERE: 
* (1) Read an input csv line from stdin 
* (2) Parse csv line into appropriate fields 
* (3) Take action based on input type: 
*  - Check-in or check-out a patient with a given ID 
*  - Add a new health data type for a given patient 
*  - Store health data in patient record or print if requested 
* (4) Continue (1)-(3) until EOF 
*/ 

/* A new struct to hold all of the values from the csv file */ 
typedef struct { 
    int iD; 
    char *time[MAXTIME + 1]; 
    int value; 
    int type; 
}csv_input; 

/* Declare an instance of the struct, and assign pointers for its values */ 
csv_input aLine; 
int *idptr; 
char timeval[MAXTIME + 1]; 
int *valueptr; 
int *typeptr; 

/*Note: because the time char is already a pointer, I did not make another one for it but instead dereferenced the pointer I was given */ 
idptr = &aLine.iD; 
int j; /* iterator variable */ 
for(j; j < MAXTIME; j++){ 
    *aLine.time[j] = timeval[j]; 
} 
valueptr = &aLine.value; 
typeptr = &aLine.type; 

/* Get the Patient ID */ 
*idptr = getchar(); 
printf("%c", aLine.iD); /* a test to see if my pointers worked and the correct value was read */ 

/*Skip the first comma */ 
int next; 
next = getchar(); 

/* get the timestamp */ 
int i; 
for(i = 0; i < MAXTIME; i++) 
{ 
    while ((next = getchar()) != ',') 
    { 
    timeval[i] = next; 
    //printf("%s", aLine.time[i]); 
    } 
} 
+0

'* aLine.time [j] = timeval [j];'指針數組未被初始化。 – wildplasser 2013-04-29 14:39:06

回答

0
char *time[MAXTIME + 1]; 

這是指針(字符指針數組)的數組,而不是字符

的陣列

崩潰來自該行

*aLine.time[j] = timeval[j]; 

因爲正如我所說aLine.time[j]是一個指針,你沒有爲FILLIN在此之前指針分配內存摹其內容

2

第一:

int j; /* iterator variable */ 
for(j; j < MAXTIME; j++){ 

您需要設置j爲某個值,j=0是有道理的。沒有這個,你正在訪問一個未初始化值的數組,你將得到UB。

第二:

/*Note: because the time char is already a pointer, 

否,time是一個指針數組,以字符,是有區別的存在。

這行:因爲一件事,你的發言but instead dereference the pointer I was given正在做出不正確的假設

*aLine.time[j] = timeval[j]; 

將無法​​正常工作。是的,你得到了一個指針數組,但是它們沒有指向任何東西,它們是未初始化的,因此在將它們初始化爲一個有效的非NULL值之前,你不能遵守它們。

我認爲你試圖做這樣的事情:

aLine.time[j] = &timeval; //set the pointer to the local static array 

但是這隻會在局部函數範圍內工作。如果你malloc的指針數組會更好。