c - 在 C 中解析 CSV 行时出现段错误

标签 c csv segmentation-fault

<分区>

我正在做一个项目,我需要将文本文件中的 CSV 行读取到我的程序中。我得到了一个代码框架,并被要求填写功能。我有一个包含我将要接收的每种类型的值的变量的结构,但我的 char 数组导致段错误。 这是我的代码的摘录。 摘录都不是给定代码的一部分,这都是我的: 由于获取时间戳空间内的代码,我的错误是段错误(核心已转储)。 我的测试文件只包含一行, 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]);
     }
}

最佳答案

首先:

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];

不会工作,因为一方面,您的声明 而是取消引用我得到的指针 做出了错误的假设。是的,您获得了一个指针数组,但它们不指向任何东西,它们未初始化,因此在将它们初始化为有效的非 NULL 值之前您无法对它们进行引用。

我想你正试图做这样的事情:

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

但这只适用于本地函数范围。如果你 malloc 到你的指针数组会更好。

关于c - 在 C 中解析 CSV 行时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16281369/

相关文章:

C 编程指针

c - C 中的子字符串(数组中的剩余部分会发生什么)

c - 尝试填充结构数组时发生访问冲突

python - 读取带有负数的文本文件时出现问题

php - 如何解析数据中包含换行符的 Excel CSV 数据?

c - 使用 GDB 在 "?? ()"中出现内存故障

c - 为什么将 char 作为参数传递给 islower() 无法正常工作?

sql - 如何使用 SQLPLUS 假脱机到 CSV 格式的文件?

c - 来自 printf() 的随机段错误,有人可以帮忙解释一下吗?

将字符串复制到数组 -- strcpy segfault