c - 从另一个 c 文件迭代 c 数组,隐藏结构变量

标签 c arrays loops

我有一个简单的结构,比如

typedef struct myPtr myPtr;

typedef struct example {

  myPtr* list_ptr;//just a list of pointers, doesnt matter for now
  int nb_elements;
  int nb_mllc;
} example;

在我的 c 文件 example.c 中,我已经实现了为此所需的所有功能,包括 malloc、realloc、free 和 add entries...

example* create_example(int num){

   example* ex = malloc(sizeof(example));
   if (ex == NULL) //do some error catching

   ex->list_ptr = malloc(sizeof(myPtr) * num);
   if (ex->list_ptr == NULL) //do some error catching

   ex->nb_mllc = num;
   ex->nb_elements = 0;

   return ex;
}

现在如果我想遍历结构的条目,我知道我可以简单地通过使用 for 循环来完成

  example* ex = create_example(10);
  //lets assume the entries are filled, so 
  // ex->nb_elements is greater than 0

 for (int i=0; i<ex->nb_elements; i++) //... do stuff

但是我想知道是否可以编写一个函数,这样我就可以在对结构一无所知的情况下遍历条目。所以我在另一个 c 文件“another_file.c”中,我只想不关心结构本身,所以只需创建它然后调用像 iterate_over 这样的函数,所以跳过编写这个循环,从那时起我还需要知道如何结构变量看起来像在我的“another_file.c”文件中。所以像

  example* ex = create_example(10);
  iterate_over(ex); //but then I dont know how to access the current element from here
  //or do something like

  while(iterate_over(ex) != NULL) //saying it is empty..

有人可以提示我如何执行此操作,因为我不知道如何隐藏此处所需的所有索引和信息..

最佳答案

我终于了解了一些很好的细节,我可以将我的循环放入宏中,我认为这是我一直在寻找的东西。

但是,我在宏中找到了一个数组的 foreach 循环示例

#define foreach(item, array) \
  for(int keep = 1, \
        count = 0,\
        size = sizeof (array) / sizeof *(array); \
    keep && count != size; \
    keep = !keep, count++) \
  for(item = (array) + count; keep; keep = !keep)

老实说,我不知道这里发生了什么,有 keep= !keep 之类的东西,所以有人可以将我与一些资源联系起来,让我可以找到这里发生的事情吗?

关于c - 从另一个 c 文件迭代 c 数组,隐藏结构变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40907311/

相关文章:

c - 我如何读取文本文件字母并保存到C中的数组中

C - 包含整数和字符串的文件(除法问题)

c - Windows gui C 在 sublime text 中构建系统

arrays - 数组中元素出现的频率

javascript - 迭代具有相同名称的对象属性

Python嵌套for循环不会在第一个循环的第二次迭代中执行第二个for循环

c - 递归释放C中的TRIE结构

php - 将每个值的位置移动到关联数组中的下一个索引

c - 有没有办法将元素添加到列表/数组? [C]

python - 迭代字典键引用的未知数量的列表,以允许比较每个列表中的值