[英]Dynamic memory allocation of a string
how to dynamically allocate memory for a string? 如何为字符串动态分配内存?
I want to take a text file as input and want to store the characters of the file to a string. 我想将文本文件作为输入,并希望将文件的字符存储到字符串中。
First I count the number of character in the text file then dynamically allocate the string for this size and then want to the copy the text to the string. 首先,我计算文本文件中的字符数,然后为该大小动态分配字符串,然后将文本复制到字符串中。
main()
{
int count = 0; /* number of characters seen */
FILE *in_file; /* input file */
/* character or EOF flag from input */
int ch;
in_file = fopen("TMCP.txt", "r");
if (in_file == NULL) {
printf("Cannot open %s\n", "FILE_NAME");
exit(8);
}
while (1)
{
ch = fgetc(in_file);
if (ch == EOF)
break;
++count;
}
printf("Number of characters is %d\n",
count);
char *buffer=(char*)malloc(count*(sizeof(char)));
}
That's a terrible solution. 那是一个糟糕的解决方案。 You can determine the size of the file using a load of methods (search for
tell
file size, and especially for fstat
), and you can just mmap
your file to memory directly, giving you exactly that buffer. 您可以确定使用的方法加载文件的大小(搜索
tell
文件大小,尤其是对fstat
),并且你可以mmap
文件到内存直接,让你正是缓冲区。
One option is to read the file a fixed-sized chunk at a time and extend the dynamic buffer as you read the file. 一种选择是一次读取固定大小的文件,并在读取文件时扩展动态缓冲区。 Something like the following:
类似于以下内容:
#define CHUNK_SIZE 512
...
char chunk[CHUNK_SIZE];
char *buffer = NULL;
size_t bufSize = 0;
...
while ( fgets( chunk, sizeof chunk, in_file ) )
{
char *tmp = realloc( buffer, bufSize + sizeof chunk );
if ( tmp )
{
buffer = tmp;
buffer[bufSize] = 0; // need to make sure that there is a 0 terminator
// in the buffer for strcat to work properly.
strcat( buffer, chunk );
bufSize += sizeof chunk;
}
else
{
// could not extend the dynamic buffer; handle as necessary
}
}
This snippet reads up to 511 characters from in_file
at a time ( fgets
will zero-terminate the target array). 此代码段一次从
in_file
读取多达511个字符( fgets
将使目标数组零终止)。 It will allocate and extend buffer
for each chunk, then concatenate the input to buffer
. 它将为每个块分配并扩展
buffer
,然后将输入连接到buffer
。 In order for strcat
to work properly, the destination buffer needs to be 0-terminated. 为了使
strcat
正常工作,目标缓冲区需要以0结尾。 This isn't guaranteed the first time around when the buffer is initially allocated, although it should be on sunsequent iterations. 尽管应该在随后的迭代中进行初始化,但这并不能保证第一次分配该缓冲区。
Another strategy is to double the buffer size each time, which results in fewer realloc
calls, but this is probably easier to grasp. 另一种策略是每一次,这能减少一倍的缓冲区大小
realloc
调用,但是这可能是更容易把握。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.