简体   繁体   English

迭代一个C数组

[英]Iterate through a C array

I have an array of structs that I created somewhere in my program. 我有一个结构数组,我在程序中的某处创建。

Later, I want to iterate through that, but I don't have the size of the array. 后来,我想迭代一遍,但我没有数组的大小。

How can I iterate through the elements? 我如何迭代元素? Or do I need to store the size somewhere? 或者我需要将尺寸存储在某个地方?

If the size of the array is known at compile time, you can use the structure size to determine the number of elements. 如果在编译时已知数组的大小,则可以使用结构大小来确定元素的数量。

struct foo fooarr[10];

for(i = 0; i < sizeof(fooarr) / sizeof(struct foo); i++)
{
  do_something(fooarr[i].data);
}

If it is not known at compile time, you will need to store a size somewhere or create a special terminator value at the end of the array. 如果在编译时不知道,则需要在某处存储大小或在数组末尾创建特殊的终止符值。

您可以在某处存储大小,或者您可以使用具有您用作标记的特殊值集的结构,就像'\\ 0'表示字符串结尾的方式相同。

It depends. 这取决于。 If it's a dynamically allocated array, that is, you created it calling malloc, then as others suggest you must either save the size of the array/number of elements somewhere or have a sentinel (a struct with a special value, that will be the last one). 如果它是一个动态分配的数组,也就是你创建它调用malloc,那么就像其他人建议你必须保存数组的大小/元素的数量或者有一个sentinel(一个具有特殊值的结构,这将是最后一个)。

If it's a static array, you can sizeof it's size/the size of one element. 如果它是一个静态数组,你可以调整它的大小/一个元素的大小。 For example: 例如:

int array[10], array_size;
...
array_size = sizeof(array)/sizeof(int);

Note that, unless it's global, this only works in the scope where you initialized the array, because if you past it to another function it gets decayed to a pointer. 请注意,除非它是全局的,否则这只适用于初始化数组的范围,因为如果将它传递给另一个函数,它会被衰减为指针。

Hope it helps. 希望能帮助到你。

I think you should store the size somewhere. 我认为你应该在某处存放大小。

The null-terminated-string kind of model for determining array length is a bad idea. 用于确定数组长度的以null结尾的字符串模型是个坏主意。 For instance, getting the size of the array will be O(N) when it could very easily have been O(1) otherwise. 例如,获得数组的大小将是O(N),否则很可能是O(1)。

Having that said, a good solution might be glib's Arrays , they have the added advantage of expanding automatically if you need to add more items. 话虽如此,一个好的解决方案可能是glib的Arrays ,如果你需要添加更多项目,它们还具有自动扩展的额外优势。

PS to be completely honest, I haven't used much of glib, but I think it's a (very) reputable library. PS是完全诚实的,我没有使用太多的glib,但我认为它是一个(非常)有信誉的库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM