我正在尝试组合我正在从文件中读取的字符中的单词。问题在于结合人物。我这样做的方法如下:
char *charArr
while( (readChar = fgetc(fp)) != EOF ){
charArr[i] = readChar;
i++;
}
答案 0 :(得分:2)
首先,您需要为charArr
缓冲区分配一些内存;如上所述,charArr
最初并未指出任何有意义的内容:
char *charArr = malloc(SOME_INITIAL_SIZE);
其中SOME_INITIAL_SIZE足以处理大多数情况。对于那些不够大的时候,你必须使用realloc()
来扩展缓冲区。这意味着您还必须跟踪缓冲区的当前大小:
size_t currentSize = 0;
size_t i = 0;
char *charArr = malloc(SOME_INITIAL_SIZE);
if (!charArr)
{
/**
* memory allocation failed: for this example we treat it as a fatal
* error and bail completely
*/
exit(0);
}
currentSize = SOME_INITIAL_SIZE;
while ((readchar = fgetc(fp)) != EOF)
{
/**
* Have we filled up the buffer?
*/
if (i == currentSize)
{
/**
* Yes. Double the size of the buffer.
*/
char *tmp = realloc(charArr, currentSize * 2);
if (tmp)
{
charArr = tmp;
currentSize *= 2;
}
else
{
/**
* The realloc call failed; again, we treat this as a fatal error.
* Deallocate what memory we have already allocated and exit
*/
free(charArr);
exit(0);
}
}
charArr[i++] = readchar;
}
如果您将数组视为字符串,请不要忘记添加0终结符。
修改强>
然而,更大的问题是为什么你认为在过滤数据之前必须将整个文件的内容读入内存?你为什么不过滤?