gpt4 book ai didi

c - getline中第二个参数的作用是什么?

转载 作者:行者123 更新时间:2023-12-03 02:12:16 26 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
char* buffer = malloc(100 * sizeof(char));
size_t n = 3;

getline(&buffer, &n, stdin);
printf("%s\n", buffer);
free(buffer);
}

我认为 getline 中的第二个参数 size_t *n 是限制读取的字符数。但是当我尝试使用更大的输入时,它仍然读取所有输入。我在手册页和网上进行了搜索,但找不到答案。谁能帮我解释一下吗?

最佳答案

来自getline man pages :

给定ssize_t getline(char **lineptr, size_t *n, FILE *stream);

If *lineptr is NULL, then getline() will allocate a buffer for storing the line, which should be freed by the user program. (In this case, the value in *n is ignored.)

Alternatively, before calling getline(), *lineptr can contain a pointer to a malloc(3)-allocated buffer *n bytes in size. If the buffer is not large enough to hold the line, getline() resizes it with realloc(3), updating *lineptr and *n as necessary.

强调我的。简而言之,更新 n 以确保线条适合。

关于c - getline中第二个参数的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41196543/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com