【发布时间】:2021-02-09 01:24:06
【问题描述】:
我在解决练习时遇到了内存分配问题。本练习的目的是创建一个接受两个参数的函数(例如“abc def gh-!” && “-”),方法是用分隔符分割字符串,在这种情况下是第二个参数,然后返回一个数组在我的 typedef 结构中,其中包含新的拆分字符串。
这是我目前的代码...
#ifndef STRUCT_STRING_ARRAY
#define STRUCT_STRING_ARRAY
typedef struct s_string_array
{
int size;
char** array;
} string_array;
#endif
string_array* my_split(char* str, char* sep) {
string_array*ptr=(string_array*)malloc(sizeof(string_array)); //Memory allocation Struct
int i;
int j;
int words;
int in_word;
i = 0;
words = 1;
while (str[i]) {
if (str[i] != *sep) {
if (!in_word) {
words++; // Count number of words inside the string
}
in_word = 1;
} else {
in_word = 0;
}
i++;
}
ptr->size = words;
ptr->array=malloc(sizeof(char*)*ptr->size); // Allocate the array of pointer inside struct
int size = 0;
i = 0;
j = 0;
while (i < ptr->size) {
while (str[j] != *sep) {
size++;
j++;
}
ptr->array[i]=malloc(sizeof(char) * (size + 1));
ptr->array[i][size+1] = '\0';
i++;
}
int c = 0;
int r = 0;
i = 1;
j = 0;
while (i < ptr->size) {
if (str[j] != *sep) {
while (str[j] != *sep) {
ptr->array[c][r++] = str[j++];
}
}
i++;
c++;
}
printf("%s\n", ptr->array[0]);
printf("Words in new Array is: %d\n", ptr->size);
printf("J is at index: %d\n", j);
printf("The character at index J is: %c\n", str[j]);
printf("The first index of the array is now at: %d\n", c);
}
int main() {
my_split("abc def gh-!", "-");
return 0;
}
返回值必须是:["abc def gh", "!"]
请帮忙。
【问题讨论】:
-
ptr->array[i]=malloc(sizeof(char) * (size + 1)); ptr->array[i][size+1] = '\0';糟糕,超出范围写入! -
分隔符是字符指针,因为它可能包含多个分隔符吗?是分隔字符串。 (例如 ” - ”)。否则,我看不出它是
char *的任何原因,而且您的代码(从错误中抽象出来)可能太简单了。 -
分隔符是一个唯一的字符,表示为字符串so(例如“-”、“”、“d”)
标签: c pointers dynamic-memory-allocation strtok