#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//the function
char* scan(char *string)
{
int c; //as getchar() returns `int`
string = malloc(sizeof(char)); //allocating memory
string[0]='\0';
for(int i=0; i<100 && (c=getchar())!='\n' && c != EOF ; i++)
{
string = realloc(string, (i+2)*sizeof(char)); //reallocating memory
string[i] = (char) c; //type casting `int` to `char`
string[i+1] = '\0'; //inserting null character at the end
}
return string;
}
char** bigScan(char **string)
{
int c;
string=malloc(sizeof(char *));
string[0]='\0';
for(int i=0;(c=getchar()!=EOF);i++)
{
*string = realloc(string, (i+2)*sizeof(char *)); //reallocating memory
string[i] = scan(string[i]); //type casting `int` to `char`
string[i+1] = '\0'; //inserting null character at the end
}
return string;
}
int main(void)
{
char **buf; //pointer to hold base address of string
buf=bigScan(buf);
printf("%s\n",buf[0] );
}
所以基本上扫描函数读取每一行直到EOF或新行.bigScan的工作是通过调用扫描函数读取多行(指向字符串的指针),直到我们点击EOF。所以基本上大扫描会返回指向指针的指针,我们可以使用它来读取整个文本。在我的方法中我做错了什么?基本上在我的bigScan中调用扫描功能,直到我点击EOF。
Ideal Input:
"Hi guys and girls
This is a message in multiple lines."
Ideal Output:
"Hi guys and girls
This is a message in multiple lines."
(c=getchar()!=EOF)
内的bigScan
无效。它将1
或0
的值赋给c,因为bool
值是!=
比较的结果。getchar()
的分配无效。你不应该为字符串bigScan
分配内存,但你应该为指针本身分配内存,即。 bigScan
。*string = realloc(string
是用于指针的终止值。不要使用string = realloc(string, ... sizeof(char*))
作为指针。NULL
存储大小。'\0'
未使用size_t
,因为两个函数中的变量a
在进入函数后立即分配。void f(int a) { a = 1; }
具有string
字符的硬限制。以下是您的功能的某种固定版本。同时也重命名了变量。并删除参数。和不同的缩进。并使用标准scan
中的i<100
ions作为原始错误检查。而使用assert
所以在#include <assert.h>
中读取的字符不会消失。我没有运行此代码,因此它有很多错误。
ungetc