我正在开展一个项目,我需要从文本文件中读取CSV行到我的程序中。我得到了一个代码框架,并要求填写功能。我有一个结构包含我将要接收的每种类型的值的变量,但我的char数组导致分段错误。 这是我的代码的摘录。 没有任何exerpt是给定代码的一部分,这是我的全部: 由于get时间戳空间中的代码,我的错误是分段错误(Core Dumped)。 我的测试文件只包含一行, 5,10:00:10,1,997
/*
* 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 :(得分:2)
首先:
int j; /* iterator variable */
for(j; j < MAXTIME; j++){
您需要将j
设置为某个值,j=0
才有意义。如果没有这个,你将访问一个具有未初始化值的数组,并且你将获得UB。
第二
/*Note: because the time char is already a pointer,
不,time
是一个指向字符的指针数组,那里存在差异。
这一行:
*aLine.time[j] = timeval[j];
不起作用,因为一方面,你的陈述but instead dereference the pointer I was given
做出了错误的假设。是的,你得到了一个指针数组,但它们没有指向任何东西,它们是未初始化的,因此你不能将它们推迟到将它们初始化为有效的非NULL值。
我认为你试图做这样的事情:
aLine.time[j] = &timeval; //set the pointer to the local static array
但这只能在本地函数范围内工作。如果对你的指针数组进行malloc操作会更好。
答案 1 :(得分:0)
char *time[MAXTIME + 1];
这是一个指针数组(指向char数组的指针)而不是一个chars数组
崩溃来自这条线
*aLine.time[j] = timeval[j];
因为我说aLine.time[j]
是一个指针而你在填充其内容之前没有为这个指针分配内存