【发布时间】:2017-06-29 06:49:04
【问题描述】:
我不明白这个函数是做什么的。谁能详细解释一下?
char *my_getline(FILE *stream) {
char *line = NULL;
size_t pos = 0;
int c;
while ((c = getc(stream)) != EOF) {
char *newp = realloc(line, pos + 2);
if (newp == NULL) {
free(line);
return NULL;
}
line = newp;
if (c == '\n')
break;
line[pos++] = (char)c;
}
if (line) {
line[pos] = '\0';
}
return line;
}
如果您可以对我的代码添加评论,我认为这会对我有所帮助。我想在一个字符串中搜索一个子字符串,我找到了这个函数代码。
这是主要功能:
int main(void) {
char *str, *sub;
size_t len1, len2, i, count = 0;
printf("Insert string :\n");
str = my_getline(stdin);
printf("insert substring :\n");
sub = my_getline(stdin);
if (str && sub) {
len1 = strlen(str);
len2 = strlen(sub);
for (i = 0; i + len2 <= len1; i++) {
if (!memcmp(str + i, sub, len2)) {
count++;
printf("Substring found at index : %d\n", i);
}
}
printf("in the number of: %d\n", count);
if (count == 0) {
printf("Substring not found\n");
}
}
free(str);
free(sub);
return 0;
}
我了解main函数,但无法理解函数my_getline中的逻辑。
请帮助我理解逻辑。谢谢!
【问题讨论】:
-
你能缩小范围吗?您了解该功能的哪些部分,哪些不了解?请在每行制作 cmets
// understood或// ??。 -
它以我能想象到的最低效的方式读取整行...