Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C结构的迭代数组_C_Arrays_Struct - Fatal编程技术网

C结构的迭代数组

C结构的迭代数组,c,arrays,struct,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 !=

假设我已经声明了一个结构

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
} 
struct mystruct{
chara[10];
双b;
} 
结构mystruct数组[20]={
{'test1',1.0},

{'test2',2.0}如果您只初始化了三个项目,那么您通常必须记住这段信息并执行以下操作

for(i=0; i<3; i++) { ... }
由于
数组[i].a
是一个字符,您应该将其与字符进行比较。巧合的是,由于一些隐式转换(字符到整数),您还应该能够将其与整数进行比较

 for( i=0; array[i].a != 0 ;i++){ ... } 

也应该可以。通过传递,您的NULL版本也应该可以工作,因为NULL只是0的一个宏(无论如何在大多数计算机体系结构上),但您不应该使用它,因为(人类)约定它只应用于空指针。

适用于接受初始值设定语法的编译器(这应该是任何标准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);
}
struct mystruct
{
chara[10];
双b;
};//添加了分号!
结构mystruct数组[20]=
{ 
{“test1”,1.0},//字符串!
{“test2”,2.0},
};
枚举{ARRAY_SIZE=sizeof(ARRAY)/sizeof(ARRAY[0]);
int i;
对于(i=0;i%f\n”,数组[i].a,数组[i].b);
}

您正在比较
数组[i]。a
与NULL的比较让我非常担心,因为您没有在中显示代码:“…在这里用3个项目初始化ok”。您的意思是
{“test1”,1.0},
等;您正在使用多字符文字,这是不可移植的。数组声明有多大区别。现在您的代码是错误的。
array[i]。a
将永远不会为空。如果我理解您的意图,您想检查
array[i].a[0]!=0
。哦,请尝试“test1”等等。我觉得你会对此更满意。@self:标准允许你编写包含多个字符的字符文字,但结果是实现定义的。ISO/IEC 9899:2011§6.4.4.4字符常量:^10…包含多个字符的整数字符常量的值(例如,“ab”),或包含不映射到单字节执行字符的字符或转义序列,是实现定义的…只需使用双引号而不是单引号。
“test1”
而不是
'test1'
。您可能需要再次检查发布的代码。当您键入这些内容时…已更改。+1和OP的注释。不要养成这种习惯。这会使代码更难阅读,尤其是您的代码变得“易更新”。假设你只有3个元素,而不是20个元素。现在假设有人跟踪你,看到代码并想添加第三个元素。好吧,看看这个,他们认为…已经有空间了,所以我们只在末尾添加它。突然你进入了未定义的行为。如果你要这样做,请确保它有良好的文档记录……然后Jonathan设置了硬限制,使我之前的评论没有意义
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);
}