gpt4 book ai didi

c - 如何清理 char* 的静态返回数组?

转载 作者:行者123 更新时间:2023-12-04 11:38:43 24 4
gpt4 key购买 nike

我想在使用后清理这个 char* 的静态数组。我想从文件中读取并将通过 fgets() 获得的行拆分为单词数组返回它并清理缓冲区 (static char *words)。但这是我对 split() 的实现,我想知道静态 char* 字是否不会导致内存泄漏,因为我无法销毁它,因为每次从文件中获取一行时我都想调用它:

#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]);
}

有什么想法吗?

最佳答案

您可以在函数的开头重置它,然后再重新使用它。基本上,您正在清除当前通话中的先前条目。

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;
}

关于c - 如何清理 char* 的静态返回数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59029162/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com