【发布时间】:2015-11-10 19:37:06
【问题描述】:
我正在编写一个 C 程序,它应该从用户的文章中读取。论文分为多个段落。
我不知道这篇文章有多少行或多少个字符,但我知道它以井号结尾(#)。我只想使用尽可能多的内存来保存这篇文章。
这是我迄今为止尝试过的:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
main(){
int size;
char *essay;
printf("\n how many characters?\n");
scanf("%d", &size);
essay =(char *) malloc(size+1);
printf("Type the string\n");
scanf("%s",essay);
printf("%s",essay );
}
正如我之前所说,我事先不知道(也不想问)字符数。如何动态分配内存以节省空间? (什么是动态内存分配?)还有另一种不依赖动态分配的内存节省方式吗?
此外,我的代码现在一次只能读取一行。如何读取多行并将它们存储为单个字符串?
这是另一个代码
#include <stdio.h>
#include <stdlib.h>
int main ()
{
char input;
int count = 0;
int n;
char* characters= NULL;
char* more_characters = NULL;
do {
printf ("type the essay:\n");
scanf ("%d", &input);
count++;
more_characters = (char*) realloc (characters, count * sizeof(char));
if (more_characters!=NULL) {
characters=more_characters;
characters[count-1]=input; }
else {
free (characters);
printf ("Error (re)allocating memory");
exit (1);
}
} while (input!='#');
printf ("the essay: ");
for (n=0;n<count;n++) printf ("%c",characters[n]);
free (characters);
}
它不工作
【问题讨论】: