【发布时间】:2017-08-10 10:26:22
【问题描述】:
我是 C 编程的新手,下面是我在访问结构元素时出现问题的一段代码。
matrix1 是struct matrix 的结构数组。我想为每个matrix1 存储元素,例如matrix1[0], matrix1[1], ...,这又是其他结构内的结构数组。有没有更好的方法将元素存储到结构中。有人可以帮我弄清楚我哪里出错了。
为什么我不能访问像matrix1[1].One[0].ChannelPin 这样的元素?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char ChannelNo[2]; // "P1"
unsigned int ChannelPin; // 23
char State; // 'o'
} test;
typedef struct {
test One[2];
test two[2];
test three[2];
test four[2];
test five;
test six[1];
} matrix;
matrix matrix1[] = {{ {{{"P4",2,'O'},{"P4",1,'O'},{"Z",0,'Z'}},
{{"P4",4,'O'},{"P4",3,'O'},{"P4",5,'O'}},
{{"0",0,'0'},{"0",0,'0'},{"0",0,'0'}},
{{"0",0,'0'},{"0",0,'0'},{"0",0,'0'}},
{{"0",0,'0'}},
{{"P1",49,'S'},{"P1",1,'G'}} },
{ {{"P4",2,'O'},{"P4",1,'O'},{"Z",0,'Z'}},
{{"P4",4,'O'},{"P4",3,'O'},{"P4",5,'O'}},
{{"0",0,'0'},{"0",0,'0'},{"0",0,'0'}},
{{"0",0,'0'},{"0",0,'0'},{"0",0,'0'}},
{{"0",0,'0'}},
{{"P1",49,'S'},{"P1",1,'G'}} } }
int main() {
printf("%d\n",matrix1[1].One[0].ChannelPin);
return 0;
}
【问题讨论】:
-
你的代码还能编译吗?
-
注意
test.ChannelNo字段,不能将其用作字符串。这是因为char字符串实际上称为 null 终止 字节字符串。 null 终止 位意味着包含两个字符的字符串需要为第三个字符(终止符)留出空间。 -
@RohanKumar No.
-
@Someprogrammerdude 谢谢你的时间。ChannelNo 的大小被声明为 2,包括空终止字符。我理解错了吗?你能告诉我如何将值存储到嵌套结构的数组中吗?我的数组大小为 37,即矩阵 matrix1[37],以及如何访问它。
-
如果你想为像
"P4"这样的字符串包含终止符,那么你需要在数组中包含三个个字符。