我无法弄清楚为什么第二个while循环没有执行.它有一个访问冲突结果[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;
}
Run Code Online (Sandbox Code Playgroud)
char* oldstr = (char*)malloc(sizeof(str));
strcpy(oldstr, str);
Run Code Online (Sandbox Code Playgroud)
您没有分配足够的空间.既然str是a char *,那么你要char *在你的平台上分配多少字节,这可能不足以容纳字符串.你要:
char* oldstr = malloc(strlen(str)+1);
strcpy(oldstr, str);
Run Code Online (Sandbox Code Playgroud)
或者,为简单起见:
char* oldstr = strdup(str);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
767 次 |
| 最近记录: |