【发布时间】:2021-05-17 16:29:07
【问题描述】:
我需要在 C 中创建 2 个单独的函数 readLine() 和 readLines()。第一个必须返回指向输入字符串的指针,第二个应该返回输入字符串的指针数组。 readLines() 以换行符终止。我遇到了一些错误,可能与内存有关,有时可以,有时不能。代码如下:
char* readLine() {
char pom[1000];
gets(pom);
char* s = (char*)malloc(sizeof(char) * strlen(pom));
strcpy(s, pom);
return s;
}
这里是 readLines()
char** readLines() {
char** lines = (char**)malloc(sizeof(char*));
int i = 0;
do {
char pom[1000];
gets(pom);
lines[i] = (char*)malloc(sizeof(char) * strlen(pom));
strcpy(lines[i], pom);
i++;
} while (strlen(lines[i - 1]) != 0);
return lines;
}
总的来说,我把这些函数称为
char* p = readLine();
char** lines = readLines();
【问题讨论】:
-
"readLines() is terminated with a new line character"-- 这是什么意思?这是否意味着函数readLines应该继续读取直到找到一个空行?或者这是否意味着readLines返回的数组应该包含一个只包含换行符的空字符串,以便标记数组的结尾?还是两者都有? -
这意味着它应该继续阅读,直到找到一个空字符串。该函数返回的是输入中空行之前的字符串数组。谢谢下面的回答,我去看看真正的qucik。
-
函数
main应该如何知道readLines返回了多少行?函数readLines是否应该用包含值NULL的指针标记数组的结尾? -
我们不能只遍历行并检查 strlen(lines[i]) == 0。然后我们知道它是空行吗?考虑到数组中有一个空行。
-
是的,这是可能的。然而,使用包含值
NULL的指针来标记数组的结尾更常见(也更有效)。