我一直在尝试创建一个拆分字符串并返回指向数组第一个元素的指针的函数。它编译没有错误,但是当我运行程序时它崩溃了。这是我的代码。有关如何解决此问题的任何帮助。谢谢。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define split_count(a) a
int count(char *str, char *sub) {
int sublen = strlen(sub);
int templen = 0;
int count = 0;
if (sublen > strlen(str))
return 0;
int i, j;
for (i = 0; i < strlen(str); i++) {
if (*(str + i) == *sub) {
templen = 1;
for (j = 1; j < sublen; j++) {
if (*(str + i + j) == *(sub + j)) {
templen += 1;
}
}
if (templen == sublen) {
count += 1;
}
templen = 0;
}
}
return count;
}
char * split(char *str, char *sep, int maxsplit) {
if (!count(str, sep))
return NULL;
char *arr[split_count(count(str, sep)) + 1];
int i, j;
int templen = 0;
int stop = 0;
int counter = 0;
for (i = 0; i < strlen(str); i++) {
if (*(str + i) == *sep) {
templen = 1;
for (j = 1; j < strlen(sep); j++) {
if (*(str + i + j) == *(sep + j)) {
templen += 1;
}
if (templen == strlen(sep)) {
arr[counter] = (char*)malloc(sizeof(char) * strlen(str));
strcpy(arr[counter], "");
int k;
for (k = stop; k < i; k++) {
*(arr[counter] + strlen(arr[counter])) = *(str + k);
*(arr[counter] + strlen(arr[counter])) = '\0';
}
stop = i + strlen(sep);
counter++;
}
}
}
}
return arr[0];
}
int main() {
char *before = "This is a house isisis is";
printf("%s\n", split(before, "is", 1));
return 0;
}