gpt4 book ai didi

c - 是否可以使用 malloc 创建结构数组?

转载 作者:太空宇宙 更新时间:2023-11-04 07:14:03 31 4
gpt4 key购买 nike

是否可以使用 malloc 创建结构数组?或者应该只使用一个循环来创建它?任何其他替代解决方案。考虑下面的程序

#include <stdlib.h>
typedef struct{
int north;
int south;
} dir;

int main()
{
dir d1[20]; // array of structures created
dir *s1 = malloc(sizeof(dir)); // can I create here array of structs?

// or should i must and use loop to create array of structs?
dir *p1[10];
for(int i=0;i<10;i++) i[p1] = malloc(sizeof(dir));
return 0;
}

我试过使用 goolging,但没有找到任何有用的帖子。非常感谢任何帮助。

更新

dir *s1 = malloc(20 * sizeof(dir));
s1[0]->north = 20;
// error: invalid type argument of '->' (have 'dir')

最佳答案

它可以在一条语句中完成。例如

dir *d1 = malloc( 20 * sizeof( dir ) ); 

访问数组中结构的数据成员的语法如下所示

d1[i].north 
d1[i].south

或者

( d1 + i )->north
( d1 + i )->south

或者

( *( d1 + i ) ).north
( *( d1 + i ) ).south

其中 i 在 [0, 19] 范围内

关于c - 是否可以使用 malloc 创建结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26347069/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com