我正在尝试在方法中使用strtok拆分字符串,但是代码不断崩溃。我想这跟calloc有关。有什么建议吗?如果将其整体放在主体中,则代码可以正常工作,但我需要一种方法。错误也很模糊,所以我真的没有任何方向。
int main(void) {
char v[] = "32939/40742/40042 32940/40743/40043 32944/40747/40044 32943/40746/40045";
printf("Length: %d", strlen(v));
int* parts = split(v, " ",strlen(v));
for (int i = 0;i < 4;i++) {
printf("Part %d : %d\n", i, parts[i]);
}
free(parts);
return 0;
}
int* split(char* str, char* delimiters, int size) { // Method to split given string into required face tokens
char** tokens = (char**)calloc((size+1), sizeof(char*)); // Array to store all tokens
for (int i = 0; i < (size + 1); i++)
tokens[i] = (char*)calloc((size + 1), sizeof(char));
char* temp = (char*)calloc((size + 1), sizeof(char)); // Array to store temp tokens
int index = 0;
temp = strtok(str, delimiters);
while (temp != NULL) { // Split using spaces
if (index < (size + 1)) {
tokens[index] = temp;
}
index++;
temp = strtok(NULL, " ");
}
int* parts = (int*)calloc((size + 1), sizeof(int)); // Array to store parts of face
for (int i = 0;i < index;i++) { // Split using /
temp = strtok(tokens[i], "/");
parts[i] = atoi(temp);
}
//free tokens, free temp
for (int i = 0; i < (size + 1); i++) //Crashing here most of the time
free(tokens[i]);
free(tokens);
free(temp);
return parts;
}