我想在使用完char*
的此静态数组后将其清除。我想从文件读取并将通过fgets()获得的行拆分为单词数组,然后将其返回并清理缓冲区(static char *words
)。但这是我对split()的实现,我想知道静态char *单词是否不会导致内存泄漏,因为我无法销毁它,因为我想在每次从文件中获取一行时都调用它: / p>
#define MAX_LENGTH 10000
char** split(char* string)
{
static char* words[MAX_LENGTH / 2];
static int index = 0;
const char* delimiter = " ";
char* ptr = strtok(string, delimiter);
while (ptr != NULL)
{
words[index] = ptr;
ptr = strtok(NULL, delimiter);
++index;
}
index = 0;
return words;
}
int main()
{
char line[] = "yes you are good ";
char **splitted = split(line);
printf("%s\n", splitted[2]);
}
有什么想法吗?
答案 0 :(得分:1)
您可以在功能开始之前将其重置,然后再使用它。基本上,您要清除当前通话中的先前条目。
char* *split(char *string){
static char *words[MAX_LENGTH / 2];
static int index = 0;
//reset
for (int i=0; i < sizeof(words)/sizeof(words[0]); i++) {
words[i] = NULL;
}
const char *delimiter=" ";
char *ptr = strtok(string,delimiter);
while (ptr!=NULL)
{
words[index]= ptr;
ptr=strtok(NULL,delimiter);
++index;
}
index=0;
return words;
}