c-如何使用Typedef Struct创建一个函数来返回一个分割字符串数组



我在解决练习时遇到了内存分配问题。本练习的目的是创建一个函数,通过使用分隔符(在本例中是第二个参数(分割字符串来获取两个参数(例如"abc def gh-!"one_answers"amp;-"(,然后返回我的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] = '';
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("%sn", ptr->array[0]);
printf("Words in new Array is: %dn", ptr->size);
printf("J is at index: %dn", j);
printf("The character at index J is: %cn", str[j]);
printf("The first index of the array is now at: %dn", c);
}
int main() {
my_split("abc def gh-!", "-");
return 0;
}

返回值必须是:["abc def gh","!"]

请帮忙。

你在找这样的东西吗?

#include <stdbool.h> /* for bool data type */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define DEFAULT_BUFFER_SIZE 8
typedef struct split_result {
size_t length;
char **tokens;
} splitted;
struct split_result split(char *target_str, char *delimiters) {
struct split_result ret = {0, NULL};
size_t buffer_size = DEFAULT_BUFFER_SIZE;
size_t temp;
ret.tokens = (char **)calloc(buffer_size, sizeof(char *));
if (!ret.tokens)
return ret;
while (true) {
target_str += strspn(target_str, delimiters);
temp = strcspn(target_str, delimiters);
if (!temp)
break;
if (temp) {
if (ret.length >= buffer_size) {
buffer_size += DEFAULT_BUFFER_SIZE;
ret.tokens = (char **)realloc(ret.tokens, buffer_size * sizeof(char *));
if (!ret.tokens)
return ret;
}
ret.tokens[ret.length] = (char *)malloc(temp + 1);
if (!ret.tokens[ret.length])
return ret;
strncpy(ret.tokens[ret.length], target_str, temp);
ret.tokens[ret.length][temp] = 0;
ret.length++;
target_str += temp;
}
}
return ret;
}
void * free_split(struct split_result *destroy) {
size_t index = 0;
while (destroy->tokens[index]) {
free(destroy->tokens[index]);
destroy->tokens[index] = NULL;
index++;
}
free(destroy->tokens);
destroy->tokens = NULL;
destroy->length = 0;
return NULL;
}
int main() {
char *text = strdup("foo.bar");
char *del = strdup(".");
struct split_result res = split(text, del);
printf("length: %ldn", res.length);
for(size_t i = 0; i < res.length; i++) {
printf("token: %sn", res.tokens[i]);
}
free_split(&res);
printf("main=%sn", text);
return 0;
}

最新更新