我是个C编程新手,我试着在不知道长度的情况下分配内存,我希望有人来写,当他结束时只需按回车键(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;发布于 2017-09-28 10:23:34
最简单的解决方案是编辑:如果您有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);使用realloc时,getline将在必要时扩大其缓冲区,因此您不需要自己处理任何事情。在这里,我从大小为0的地方开始,这样它也可以为我完成初始的malloc!但是你也可以给它分配你自己的缓冲区,如果需要的话,就让getline来放大它。
在调用getline之后,chars_read将保存读取的字符总数,包括尾随的换行符。如果这是-1,那么一定是出了问题,比如文件结束或内存分配失败。bufsize将保留buffer的新大小,该大小可能已更改,也可能未更改。
有关详细信息,请参阅the man page。
https://stackoverflow.com/questions/46459894
复制相似问题