2
我不确定如何通过一个连续的动态分配内存块进行索引。使用malloc结构的内存块的索引c
typedef struct p
{
char name[30];
int age;
} Person;
...在主
//Create enough memory to hold 20 'Person's
Person *people = (Person *)malloc(sizeof(Person) * 20);
我怎样才能通过索引此设置变量名称和每个人的年龄?鉴于该文件具有适当的布局。
我尝试了以下,但经过几次迭代后,我得到了段错误。
int i;
for (i = 0; i < 20; i++) {
fscanf(file, "%s", (people + (i * sizeof(Person)))->name);
fscanf(file, "%d", &((people + (i * sizeof(Person)))->age));
}
有没有办法使用'[x]'进行索引?
谢谢
如果你只想用C语言,你为什么标记C++? –
你为什么不写'fscanf(文件,“%d”,&people [i] .age);'等等? –