C迭代结构数组

标签 c arrays struct

说我已经声明了一个结构

struct mystruct {
  char a[10];
  double b;
} 

struct mystruct array[20] = { 
   {'test1',1.0},
   {'test2',2.0}  <---- I just want to declare 2 items first because I am going to add new ones later.
};
int i;
for( i=0; array[i].a != NULL ;i++){ 
    ....  <--- so here I just want to display what is initialized first
} 

但是,for 循环显示超过 2 个项目(即超过 20 个项目,但其余的都是垃圾)。我只想显示当前仅初始化的内容,即使我声明要存储其中的 20 个。怎么做?谢谢。

我使用的是 C90 标准。 另外,假设我将来添加了更多项目,但仍然少于 20 个项目,我只想显示到“最后一个有效项目”。

最佳答案

对于接受初始化器语法的编译器(应该是任何标准 C 编译器),您应该能够编写:

struct mystruct
{
  char a[10];
  double b;
};  // semi-colon added!

struct mystruct array[20] =
{ 
   { "test1", 1.0 },  // character strings!
   { "test2", 2.0 },
};
enum { ARRAY_SIZE = sizeof(array) / sizeof(array[0]) };

int i;
for (i = 0; i < ARRAY_SIZE && array[i].a[0] != '\0'; i++)
{ 
    printf("[%s] => %f\n", array[i].a, array[i].b);
}

关于C迭代结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20320116/

相关文章:

c - UDP 数据报中分配的端口号和 sockaddr_in 中的端口号

php - 将 arrayaccess 与静态类一起使用

arrays - 如何在 postgres 9.3 中将 json 数组转换为 postgres int 数组

Ruby 数组数组和 map 方法

c - C 中的结构体和指针

c - C语言从String中读取数据

python - 使用 Python/C API 将 Python 列表传递给 C 函数

c - 显式转换总是与隐式转换相同吗?

c++ - 如何将 "struct Node"转换为 "class Node"?

c - 在c中定义数据类型的两种方法。我应该选择哪一个?