简体   繁体   English

使用C中的结构的malloc遍历内存块

[英]Index through chunk of memory using malloc of structures in c

I am unsure how to index through one contiguous chunk of dynamically allocated memory. 我不确定如何对动态分配的内存的一个连续块进行索引。

typedef struct p
{
    char name[30];
    int age;
} Person;

...in main ...主要

//Create enough memory to hold 20 'Person's
Person *people = (Person *)malloc(sizeof(Person) * 20);

How can I index through this to set variables name and age of each person? 我如何通过此索引来设置每个人的变量名称和年龄? Given that file has proper layout. 鉴于该文件具有正确的布局。

I attempted the following, but after a couple iterations, I got a segfault. 我尝试了以下操作,但是经过几次迭代,我遇到了段错误。

int i;
for (i = 0; i < 20; i++) {
    fscanf(file, "%s", (people + (i * sizeof(Person)))->name);
    fscanf(file, "%d", &((people + (i * sizeof(Person)))->age));
}    

Is there a way to index using '[x]'? 有没有一种方法可以使用'[x]'进行索引?

Thank you 谢谢

I think the confusion here is about how pointer arithmetic works. 我认为这里的困惑是关于指针算法的工作原理。

When you add x to a pointer of type T* , it doesn't add x to the base pointer but x * sizeof(T) . x添加到类型T*的指针时,它不会将x添加到基本指针,而是x * sizeof(T) (With exception to void* . Pointer arithmetic is undefined on void* ) (除了void* 。指针算法在void*上未定义)

So, to fix your case you can use (people + i) instead of (people + i* sizeof(..)) 因此,要解决您的问题,您可以使用(people + i)代替(people + i* sizeof(..))

Another way of doing it would be to use - people[i] . 做到这一点的另一种方法是使用people[i]

Memory pointed to by pointers can be indexed into just like arrays of the same type. 指针所指向的内存可以像相同类型的数组一样被索引。

I hope this clears the confusion. 我希望这能消除混乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM