你有几个问题:
#include <stdio.h>
#include <time.h>
为什么这个标题?
#include <stdlib.h>
int main()
{
char ch, *ptrChFromFile;
int strSize;
该变量需要有一个有用的起始值。
ptrWordsFromFile = (char*)malloc(sizeof(char));
无需施展。
if(ptrChFromFile == NULL)
{
puts("COULDN'T ALLOICATE MEMORY");
exit(EXIT_FAILURE);
}
while((ch = getchar()) != EOF)
getchar
返回和int
, not a char
.
{
ptrChFromFile = (char*)realloc(ptrChFromFile, strSize * sizeof(char)+1);
我们需要比以前多一个字符以及额外的空间0
。
您应该将+2(而不是+1)添加到元素数量中:(strSize+2) * sizeof(<any type>)
通常你不应该直接分配结果realloc
指向同一个指针。如果失败,您将丢失旧的指针值。再说一遍:不需要演员。
if(ptrChFromFile == NULL)
{puts("failed to alloicate memory");}
如果失败,则无法继续!退出程序如上
*ptrChFromFile = ch;
您将字符放在放大的缓冲区的开头。你应该在最后添加。
strSize++;
}
现在内存中有一堆字符,但字符串没有终止符。
free(ptrChFromFile);
return 0;
}
修复后如下所示:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int ch;
char *ptrChFromFile;
int strSize = 0;
ptrWordsFromFile = malloc(sizeof(char));
if (ptrChFromFile == NULL)
{
puts("COULDN'T ALLOICATE MEMORY");
exit(EXIT_FAILURE);
}
while ((ch = getchar()) != EOF)
{
ptrChFromFile = realloc(ptrChFromFile, (strSize+2) * sizeof(char));
if (ptrChFromFile == NULL)
{
puts("failed to allocate memory");
exit(EXIT_FAILURE);
}
ptrChFromFile[strSize] = ch;
strSize++;
}
ptrChFromFile[strSize] = 0;
// Now add detection and storing of separate words
// (You might omit storing words that are too short)
// Select random words and add together.
free(ptrChFromFile);
return 0;
}