【问题标题】:How to create a dynamic array of strings in C using malloc如何使用 malloc 在 C 中创建动态字符串数组
【发布时间】:2012-10-28 13:03:59
【问题描述】:

如何在没有固定长度的项目或字符时创建字符串数组。我是指针和 c 的新手,我无法理解此处发布的其他解决方案,因此我的解决方案发布在下面。希望它可以帮助其他人。

【问题讨论】:

  • 您是在寻找锯齿状数组(不同长度的数组组成的数组),还是 X*Y 固定大小的数组?您是在寻找字符串的二维数组(==指向 char 的指针),还是在寻找指向字符串数组的指针数组(==指向 char 的指针),还是在寻找 char 的 3 维数组数组中没有指针?
  • 当我不知道字符串的数量或长度时,我正在寻找一种将字符串存储在数组中并像 string1 = array[1] 等那样访问它们的方法。那是指向字符指针的指针吗?
  • 好的,所以您实际上是在寻找单个字符串数组(=char 指针)。将其视为 2D 数组可能没有帮助(即使从某种角度来看确实如此)。
  • OP 想要一个指向字符的 1d 数组。因此,相应地调整问题的标题可能是个好主意。

标签: c arrays malloc realloc


【解决方案1】:
char **twod_array = NULL;

void allocate_2darray(char ***source, int number_of_slots, int length_of_each_slot)
{
   int i = 0;
   source = malloc(sizeof(char *) * number_of_slots);
   if(source == NULL) { perror("Memory full!"); exit(EXIT_FAILURE);}
   for(i = 0; i < no_of_slots; i++){
      source[i] = malloc(sizeof(char) * length_of_each_slot);
      if(source[i] == NULL) { perror("Memory full!"); exit(EXIT_FAILURE);}
   }
} 

// 示例程序

int main(void) { 
   allocate_2darray(&twod_array, 10, 250); /*allocate 10 arrays of 250 characters each*/ 
   return 0;
}

【讨论】:

  • allocate_2darray 函数返回时,您的source 指针将丢失。您应该将参数类型更改为char*** 并将其作为&amp;twod_array 传递。此外,由于您分配的是大小一致的数组,因此如果每个字符串的长度变化很大,则此解决方案不会很好。
  • 你有不同长度的 realloc。我不明白源指针丢失了,你在传递指针。
  • 是的,您正在按值传递指针。原始指针未被修改。函数返回后twod_array 将是NULL。您需要将指针传递给指针本身,因此需要char***。我知道,这很令人困惑。
  • 查看我在答案中发布的代码。这就是我所说的那种事情。
【解决方案2】:

只需将 argv 项目栏的第一项设为数组。

char **dirs = NULL;
int count = 0;
for(int i=1; i<argc; i++)
{
    int arraySize = (count+1)*sizeof(char*);
    dirs = realloc(dirs,arraySize);
    if(dirs==NULL){
        fprintf(stderr,"Realloc unsuccessful");
        exit(EXIT_FAILURE);
    }
    int stringSize = strlen(argv[i])+1;
    dirs[count] = malloc(stringSize);
    if(dirs[count]==NULL){
        fprintf(stderr,"Malloc unsuccessful");
        exit(EXIT_FAILURE);
    }
    strcpy(dirs[count], argv[i]);
    count++;
}

【讨论】:

  • 您应该将int arraySize = (count+1)*sizeof(dirs); 更改为int arraySize = (count+1)*sizeof(char*);。从语义上讲,您的代码有点不正确,因为dirschar**,但您分配的是char*。实际上,这两种方式都不应该有所不同,因为sizeof(char**) == sizeof(char*)
  • 你说得对,我已经编辑了它更有意义,因为 dirs 是一个指针数组
【解决方案3】:

你的很接近,但是你分配主数组的次数太多了。

char **dirs = NULL;
int count = 0;

dirs = malloc(sizeof(char*) * (argc - 1));

if(dirs==NULL){
    fprintf(stderr,"Char* malloc unsuccessful");
    exit(EXIT_FAILURE);
}

for(int i=1; i<argc; i++)
{
    int stringSize = strlen(argv[i])+1;
    dirs[count] = malloc(stringSize);
    if(dirs[count]==NULL){
        fprintf(stderr,"Char malloc unsuccessful");
        exit(EXIT_FAILURE);
    }
    strcpy(dirs[count], argv[i]);
    count++;
}

【讨论】:

  • 是的,这更适合于 argv 的情况,我实际上只是使用 argv 作为示例来说明如果我们不知道 argc 时该怎么做
猜你喜欢
  • 2017-03-29
  • 2011-08-21
  • 2016-02-23
  • 2019-04-18
  • 2012-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多