【问题标题】:How to create a function using a Typedef Struct to return an array of split strings如何使用 Typedef Struct 创建函数以返回拆分字符串数组
【发布时间】: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-&gt;array[i]=malloc(sizeof(char) * (size + 1)); ptr-&gt;array[i][size+1] = '\0'; 糟糕,超出范围写入!
  • 分隔符是字符指针,因为它可能包含多个分隔符吗?是分隔字符串。 (例如 ” - ”)。否则,我看不出它是 char * 的任何原因,而且您的代码(从错误中抽象出来)可能太简单了。
  • 分隔符是一个唯一的字符,表示为字符串so(例如“-”、“”、“d”)

标签: c pointers dynamic-memory-allocation strtok


【解决方案1】:

你在寻找这样的东西吗?

#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: %ld\n", res.length);

    for(size_t i = 0; i < res.length; i++) {
        printf("token: %s\n", res.tokens[i]);
    }

    free_split(&res);
    printf("main=%s\n", text);

    return 0;
}

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2019-06-13
  • 1970-01-01
  • 2013-01-14
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-07
  • 2021-03-25
相关资源
最近更新 更多