所以我的prgrm工作正常,直到我试图重新分配一个指针,但它并没有一直崩溃。有时它确实如此,有时它运行得很好。有人请告诉我我的代码有什么问题吗?
#include <stdio.h>
#include <cstdlib>
#include <cstring>
char getword(char[]); //return length
int main()
{
static char buffer[100];
int wcount = 5, n = 0;
char **p = (char**) malloc (wcount);
int len = getword(buffer);
while (len && n < wcount)
{
p[n] = (char *) malloc (len);
strncpy(p[n++], buffer, len);
len = getword(buffer);
if (n == wcount)
{
wcount += 10;
char** temp = (char**) realloc (p, wcount);
if (temp == NULL)
break;
else
p = temp;
}
}
return 0;
}
char getword(char buffer[])
{
int len = 0;
char c = getchar();
if (c == EOF)
return len;
while (c == 32 || c == '\n' || c == '\t' || c == '\v')
{
c = getchar();
}
do
{
buffer[len++] = c;
c = getchar();
}
while (c != 32 && c != '\n' && c != '\t' && c != '\v' && c != EOF);
buffer[len] = 0;
return ++len;
}
答案 0 :(得分:2)
char **p = (char**) malloc (wcount);
分配wcount
个字节,而不是wcount
个指针。同样realloc
。