gpt4 book ai didi

c 在不知道长度的情况下分配内存

转载 作者:行者123 更新时间:2023-11-30 14:54:49 25 4
gpt4 key购买 nike

我是c编程新手,我试图在不知道长度的情况下分配内存,我希望有人写,当他结束时只需按回车 while(c != '\n')但我不知道该怎么做。

puts("Enter a text, when you done write the e then enter: ");
char *arr = (char*)malloc(1 * sizeof(char));
while (getchar != EOF)
{
if(arr == NULL)
{
printf("Error: memory not allocated \n");
exit(1);
}
arr[count] = getchar();
arr = realloc(arr, count + 1);
}
return arr;

最佳答案

最简单的解决方案编辑:如果您有 POSIX 是使用 getline 函数,它会自动分配内存。

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

/* ... other stuff here ... */

char *buffer = NULL;
size_t bufsize = 0;
ssize_t chars_read;

/* optional: set bufsize to something positive, then set buffer = malloc(bufsize); */

chars_read = getline(&buffer, &bufsize, stdin);

/* do stuff with buffer */

free(buffer);

getline 将在必要时使用 realloc 扩大其缓冲区,因此您无需自己处理任何事情。在这里,我以零大小开始它,这样它也会为我执行初始 malloc !但您也可以给它自己分配的缓冲区,并在必要时让 getline 扩大它。

调用getline后,chars_read将保存读取的字符总数,包括尾随换行符。如果这是 -1 则表示出现问题,例如文件结束或分配内存失败。 bufsize 将保存 buffer 的新大小,该大小可能已更改,也可能未更改。

参见the man page了解更多信息。

关于c 在不知道长度的情况下分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46459894/

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