我正在编写一个函数来读取在开始处理输入行的其余部分之前必须消耗前导空格的字符输入。我成功读取了输入的前导空白字符(如果存在)。但是对于我的生活,当我尝试阅读其余部分时,我无法弄清楚何时遇到seg故障。我正在使用ansi C.这是我的代码:
void readCharLine(char **line_address) {
int c;
int index = 0;
*line_address = malloc(35 * sizeof(char));
c = getchar();
/*Consume white spaces*/
while ((c == ' ') && (index < 35)) {
c = getchar();
index++;
}
c = getchar();
/*read rest of line*/
while(c != '\n') {
*line_address[index] = c;
c = getchar();
index++;
}
}
我按如下方式调用readCharLine:
readCharLine(&node -> input);
其中node是声明如下的结构:
/*Node declaration*/
typedef struct {
char *input;
struct Node *next;
} Node;
谢谢!
答案 0 :(得分:1)
即使您丢弃的字符,您的递增index
也是如此,因此您可能正在写出数组的末尾。
您可能还希望while(c != '\n') {
为while(index < 35 && c != '\n') {
- 根据您是否需要0终止字符串进行调整。