gpt4 book ai didi

c - 在 C 中用 strtok 分割字符串

转载 作者:太空宇宙 更新时间:2023-11-04 05:41:02 25 4
gpt4 key购买 nike

我不明白为什么第二个 while 循环没有执行。它在 result[count] = atoi 上存在访问冲突......我认为添加 strcpy 会有所帮助,因为我意识到原始字符串正在被修改,但它没有任何区别。另外,我实际上使用的是 C++,但大部分源代码都在 C 中,速度是必需的。

int* split(const char* str, const char* delim)
{
char* tok;
int* result;
int count = 0;

char* oldstr = (char*)malloc(sizeof(str));
strcpy(oldstr, str);

tok = strtok((char*)str, delim);
while (tok != NULL)
{
count++;
tok = strtok(NULL, delim);
}

result = (int*)malloc(sizeof(int) * count);

count = 0;
tok = strtok((char*)oldstr, delim);
while (tok != NULL)
{
result[count] = atoi(tok);
count++;
tok = strtok(NULL, delim);
}
return result;
}

最佳答案

    char* oldstr = (char*)malloc(sizeof(str));
strcpy(oldstr, str);

您没有分配足够的空间。由于 str 是一个 char *,因此您正在分配一个 char * 在您的平台上占用的字节数,这可能不足以容纳一个字符串。你想要:

    char* oldstr = malloc(strlen(str)+1);
strcpy(oldstr, str);

或者,为了简单起见:

    char* oldstr = strdup(str);

关于c - 在 C 中用 strtok 分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19233387/

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