我是使用struct的新手,希望你能帮助我。我想要一个嵌套结构,使得 A 的成员是 B 类型结构。到目前为止我的代码如下所示。
typedef struct B
{
int b1;
} b;
typedef struct A
{
b a1;
}a;
但是我还需要“a1”成为动态二维数组,所以我执行了以下代码(不确定这是否正确,因为我为此使用了指向指针的指针,以使“数组”大小为在运行时设置):
typedef struct B
{
int b1;
} b;
typedef struct A
{
b **a1;
}a;
为了存储内存,我使用了malloc(不包括错误检测部分)。我需要通过 x 来引用和比较 a1 的每个成员,如下所示(其中 a 和 b 是整数)。我可以这样做吗?:
a* one;
b** two;
one= malloc(10* sizeof(a*));
two= malloc(10* sizeof(b*));
for(x = 1; x <= 10; x++)
{
two[x] = malloc(10* sizeof(b));
}
if(one[x].two[a][b] == x)
one[x].two[a][b].b1 =2;
抱歉,如果我的代码根本没有意义。
最佳答案
I also need 'a1' to be a 2d array, so I did the following code (not sure if this is right):
typedef struct B { int b1; } b; typedef struct A { b **a1; }a;
代码提供了有效的 C 声明,但看不到二维数组。成员(member)a1
的struct A
是一个指向 struct B
的指针,这根本不是一回事。例如,如果您确实想声明一个二维数组,那么您必须给出它的边界
typedef struct A {
b a1[5][7];
} a;
但是,如果您直到运行时才知道所需的大小,那么双指针确实是您想要的 - 只是不要将它与二维数组混淆。
To store memory I used malloc(didnt include the error detection part). I need to refer and compare each member of a1 by x, shown below (where a and b are integers).
嗯,不,a
和b
不能是整数,因为您已经在同一范围内将它们用作类型名称。
Can I do this?:
a* one; b** two; one= malloc(10* sizeof(a*)); two= malloc(10* sizeof(b*)); for(x = 1; x <= 10; x++) { two[x] = malloc(10* sizeof(b)); }
除了已经提到的名称冲突之外,您分配的 one
是错的。应该是...
one = malloc(10 * sizeof(a));
...甚至更好...
one = malloc(10 * sizeof(*one));
。您对 two
的分配和two[x]
都可以,但是如果按照与上面的后一个示例相同的方式重写它们会更好。
if(one[x].two[a][b] == x) one[x].two[a][b].b1 =2;
one[x].two[i][j]
的类型(对于整数 i
和 j
)是 b
,也就是说struct B
。 x
的类型是 int
。这些是不具有可比性的,所以不,您不能计算 if
中的表达式。健康)状况。分配给one[x].two[a][b].b1
不过没关系。
关于c - 如何在 C 中使用另一个结构体内部的结构体(同时使用 malloc 和 2D 数组?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38444967/