【发布时间】:2016-02-18 02:59:20
【问题描述】:
我正在编写一个函数来读取字符输入,它必须在开始处理输入行的其余部分之前消耗前导空格。我成功读取了输入的前导空白字符(如果存在)。但是对于我的一生,当我尝试阅读其余部分时,我无法弄清楚何时会出现段错误。我正在使用 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;
谢谢!
【问题讨论】:
-
请注意,您丢弃了第一个(可能只有)非空白字符。您还需要测试 EOF(您正在使用
int c;这很好 - 它允许您可靠地测试 EOF)。您可能想查看<ctype.h>和isspace()或isblank()。