如何附加到c中的指针数组

时间:2014-04-23 06:02:39

标签: c arrays pointers

我有一个指向结构的指针数组,我正在尝试找到一种方法来填充数组中的第一个NULL指针,并使用指向结构的新指针。即我想在数组的末尾添加一个新元素。 我尝试了这样的for循环:

struct **structs;

int i;
for(i = 0; i < no_of_pointers; i++) {
        if (structs[i] == NULL) {
              structs[i] = &struct;
        }
}

理论上,这将通过数组,当它找到一个空指针时,它会初始化它。我现在意识到它会初始化所有空指针,而不仅仅是第一个,但是当我运行它时它甚至不会这样做。我尝试了一个带有条件的while循环while(structs [i]!= NULL)并且这种情况一直持续下去,让我觉得问题在于我是如何使用NULL的。 将新元素添加到此类数组的正确方法是什么? 是否有一些我不知道的函数如append(structs,struct)? 谢谢!

2 个答案:

答案 0 :(得分:2)

C中数组的长度是固定的,在定义数组后无法更改它,这意味着您无法将元素添加到数组的末尾。但是,除非您定义了常量数组,否则可以为数组的元素指定新值。根据你的问题描述,我相信这就是你想要的。

另请注意,正如其他人已经在评论中指出的那样,struct是C的关键字,因此

  1. 您不能将其用作类型名称(就像您在struct **structs中所做的那样)

  2. 您也不能将其用作变量名称(就像您在structs[i] = &struct;中所做的那样)

  3. 这是一种方法:

    1. 正确定义数组

      struct struct_foo **structp;
      
      structp = malloc (no_of_elements * sizeof(*structp));
      if (structp == NULL) {
              /* error handle */
      }
      

      注意,此处structp的元素未初始化,您需要正确初始化它们。这就是我们在第2步中要做的事情。

    2. 使用structp执行某些操作,可能会将其所有元素初始化为NULL或某些无 - NULL

    3. NULL中找到第一个没有 - structp元素,并为其指定一个新值

      struct struct_foo foo;
      
      for (i = 0; i < no_of_elements; i++) {
              if (structp[i] == NULL) {
                      structp[i] = &foo;
                      break;
              }
      }
      

      请注意,此foo也未初始化,您可能需要先将其初始化,或者稍后再进行初始化。

答案 1 :(得分:0)

根据man malloc

       void *malloc(size_t size);
       void free(void *ptr);
       void *calloc(size_t nmemb, size_t size);
       void *realloc(void *ptr, size_t size);
       void *reallocarray(void *ptr, size_t nmemb, size_t size);

...

    The reallocarray() function  changes  the  size  of  the  memory  block
    pointed  to  by  ptr to be large enough for an array of nmemb elements,
    each of which is size bytes.  It is equivalent to the call

           realloc(ptr, nmemb * size);

尝试实现这样的系统

struct **structs;

int new_struct() {
    static int i = 0; // index of last allocated struct

    i++;
    struct *structp = malloc(sizeof(struct)); // new structure
    // initialize structp here

    reallocarray(structs, i, sizeof(struct));
    structs[i] = structp;

    return i; // use structs[index] to get
}

然后您可以调用 new_struct(),它调整 structs 数组的大小并将 structp 附加到它。最重要的是

  • a) create_struct 返回新创建的结构体的索引,并且
  • b) 它存储一个 static int i,用于跟踪 structs 的大小。
相关问题