Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 动态数组的内存分配_C_Split_Dynamic Memory Allocation_C Strings_Function Definition - Fatal编程技术网

C 动态数组的内存分配

C 动态数组的内存分配,c,split,dynamic-memory-allocation,c-strings,function-definition,C,Split,Dynamic Memory Allocation,C Strings,Function Definition,解决练习时,我陷入了内存分配问题 练习要求: 创建一个函数,该函数根据分隔符拆分字符串。 第二个参数是唯一的字符分隔符。 函数应该返回一个数组,该数组包含一个在分隔符之间包装的字符串 例如: Input: "abc def gh-!" && "-" Output: ["abc def gh", "!"] 代码: #include<stdlib.h> typedef struct s_string_array { int size; char**

解决练习时,我陷入了内存分配问题

练习要求: 创建一个函数,该函数根据分隔符拆分字符串。 第二个参数是唯一的字符分隔符。 函数应该返回一个数组,该数组包含一个在分隔符之间包装的字符串

例如:

Input: "abc def gh-!" && "-"
Output: ["abc def gh", "!"]
代码:

#include<stdlib.h>
  typedef struct s_string_array {
    int size;
    char** array;
  } string_array;


string_array* my_split(char* a, char* b) {

  //Memory allocation part:

  string_array*ptr=(string_array*)malloc(sizeof(string_array));
  int count=0;
  for(int i=0;a[i]!='\0';i++)
  {
   if(a[i]==b[0])
   {
    count++;
   }
  }
  ptr->size=count+1;
  ptr->array=malloc(sizeof(char*)*ptr->size);
  int size2=0;
  int q=0;
  for(int i=0;i<ptr->size;i++)
  {
      for(;a[q]!=b[0];q++)
      {
       size2++;
      }
      ptr->array[i]=malloc(sizeof(char)*(size2+2));
      ptr->array[i][size2+1]='\0';
      q+=2;
  }

  //Filling the array:

  int c=0;
  for(int i=0;a[i]!='\0';i++)
  {
    if(a[i]!=b[0]){
     for(int j=i,r=0;a[j]!=b[0];j++,r++)
     {
      ptr->array[c][r]=a[j];
     }
     c++;
    }
  }
  return ptr;
}
#包括
typedef结构s_字符串_数组{
整数大小;
字符**数组;
}字符串数组;
字符串数组*我的拆分(字符*a,字符*b){
//内存分配部分:
字符串数组*ptr=(字符串数组*)malloc(sizeof(字符串数组));
整数计数=0;
对于(int i=0;a[i]!='\0';i++)
{
如果(a[i]==b[0])
{
计数++;
}
}
ptr->size=count+1;
ptr->array=malloc(sizeof(char*)*ptr->size);
int size2=0;
int q=0;
for(int i=0;isize;i++)
{
对于(;a[q]!=b[0];q++)
{
size2++;
}
ptr->array[i]=malloc(sizeof(char)*(size2+2));
ptr->array[i][size2+1]='\0';
q+=2;
}
//填充阵列:
int c=0;
对于(int i=0;a[i]!='\0';i++)
{
如果(a[i]!=b[0]){
对于(int j=i,r=0;a[j]!=b[0];j++,r++)
{
ptr->array[c][r]=a[j];
}
C++;
}
}
返回ptr;
}

这给了我一个错误。有人能解释一下我做错了什么吗?

我想你走错方向了。当我读到这篇文章时:

函数应返回包含字符串的数组

它告诉我函数将返回一个指向以零结尾的字符数组(即C样式的字符串)的字符指针

换句话说,你们试图返回的是一条通往复杂的道路

这样做应该可以:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

char* my_split(const char* str, const char sep)
{
    const char* p = str;
    size_t len = 0;
    size_t words = 1;

    // Count the number of chars to copy and the number of words
    while (*p)
    {
        if (*p == sep) ++words; else ++len;
        ++p;
    }

    if (len == 0)
    {
        char* out = malloc(3);
        assert(out);
        strcpy(out, "[]");
        return out;
    }

    // Calculate required memory
    size_t total =
                    1 +              // termination
                    2 +              // [ and ]
                    2 * words +      // " and " around each word
                    2 * (words-1) +  // the , and space between words
                    len;             // the strings

    char* out = calloc(total, 1);
    assert(out);
    strcpy(out, "[\"");
    size_t index = 2;
    p = str;
    while(*p)
    {
        if (*p == sep)
        {
            // Word finished prepare the next word (if any)
            strcat(out, "\"");
            ++index;
            if (*(p+1))
            {
                strcat(out, ", \"");
                index +=3;
            }
        }
        else
        {
            out[index] = *p;
            ++index;
        }
        ++p;
    }
    strcat(out, "\"]");

    // Verify the malloc size
    assert((total-1) == strlen(out));

    return out;

}

int main()
{
  char* input1 = "abc def gh-!";
  char* output1 = my_split(input1, '-');
  printf("%s\n", output1);
  free(output1);

  char* input2 = "a-b-c-d-e-f-g";
  char* output2 = my_split(input2, '-');
  printf("%s\n", output2);
  free(output2);

  return 0;
}

我认为你走错了方向。当我读到这篇文章时:

函数应返回包含字符串的数组

它告诉我函数将返回一个指向以零结尾的字符数组(即C样式的字符串)的字符指针

换句话说,你们试图返回的是一条通往复杂的道路

这样做应该可以:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

char* my_split(const char* str, const char sep)
{
    const char* p = str;
    size_t len = 0;
    size_t words = 1;

    // Count the number of chars to copy and the number of words
    while (*p)
    {
        if (*p == sep) ++words; else ++len;
        ++p;
    }

    if (len == 0)
    {
        char* out = malloc(3);
        assert(out);
        strcpy(out, "[]");
        return out;
    }

    // Calculate required memory
    size_t total =
                    1 +              // termination
                    2 +              // [ and ]
                    2 * words +      // " and " around each word
                    2 * (words-1) +  // the , and space between words
                    len;             // the strings

    char* out = calloc(total, 1);
    assert(out);
    strcpy(out, "[\"");
    size_t index = 2;
    p = str;
    while(*p)
    {
        if (*p == sep)
        {
            // Word finished prepare the next word (if any)
            strcat(out, "\"");
            ++index;
            if (*(p+1))
            {
                strcat(out, ", \"");
                index +=3;
            }
        }
        else
        {
            out[index] = *p;
            ++index;
        }
        ++p;
    }
    strcat(out, "\"]");

    // Verify the malloc size
    assert((total-1) == strlen(out));

    return out;

}

int main()
{
  char* input1 = "abc def gh-!";
  char* output1 = my_split(input1, '-');
  printf("%s\n", output1);
  free(output1);

  char* input2 = "a-b-c-d-e-f-g";
  char* output2 = my_split(input2, '-');
  printf("%s\n", output2);
  free(output2);

  return 0;
}

对于初学者,此函数声明

string_array* my_split(char* a, char* b) {
这没有多大意义。第一个参数应具有限定符const,因为传递的字符串未在函数中更改,第二个参数不得为指针。此外,从函数返回指向
string\u数组类型的对象的指针也是毫无意义的

该函数应至少声明为

string_array my_split( const char *s, char c ) {
这个环路

  int count=0;
  for(int i=0;a[i]!='\0';i++)
  {
   if(a[i]==b[0])
   {
    count++;
   }
  }
不计算由字符
b[0]
分隔的子字符串的数量,因为这些字符可以在没有中间字符的情况下彼此跟随。比如这个字符串

"---A-"
只有一个子字符串
“A”
,前提是分隔符为
“-”

不清楚为什么
ptr->size
设置为值
count+1

由于源字符串可以从单独的字符开始,因此此循环

  for(;a[q]!=b[0];q++)
  {
   size2++;
  }
将不会作为此内存分配的结果进行迭代

  ptr->array[i]=malloc(sizeof(char)*(size2+2));
没有道理

您必须在外部循环中将变量size_t重新初始化为零

  int size2=0;
  int q=0;
  for(int i=0;i<ptr->size;i++)

对于初学者,此函数声明

string_array* my_split(char* a, char* b) {
这没有多大意义。第一个参数应具有限定符const,因为传递的字符串未在函数中更改,第二个参数不得为指针。此外,从函数返回指向
string\u数组类型的对象的指针也是毫无意义的

该函数应至少声明为

string_array my_split( const char *s, char c ) {
这个环路

  int count=0;
  for(int i=0;a[i]!='\0';i++)
  {
   if(a[i]==b[0])
   {
    count++;
   }
  }
不计算由字符
b[0]
分隔的子字符串的数量,因为这些字符可以在没有中间字符的情况下彼此跟随。比如这个字符串

"---A-"
只有一个子字符串
“A”
,前提是分隔符为
“-”

不清楚为什么
ptr->size
设置为值
count+1

由于源字符串可以从单独的字符开始,因此此循环

  for(;a[q]!=b[0];q++)
  {
   size2++;
  }
将不会作为此内存分配的结果进行迭代

  ptr->array[i]=malloc(sizeof(char)*(size2+2));
没有道理

您必须在外部循环中将变量size_t重新初始化为零

  int size2=0;
  int q=0;
  for(int i=0;i<ptr->size;i++)
六羟甲基三聚氰胺六甲醚。。。“函数应该返回一个包含字符串的数组”不确定,但听起来好像函数应该只返回一个字符指针。换句话说,你的方法似乎太复杂了。。。“函数应该返回一个包含字符串的数组”不确定,但听起来好像函数应该只返回一个字符指针。换句话说,你的方法似乎太复杂了