我有一个动态分配的结构数组。指向该数组的指针被传递给其他函数。
struct body{
char* name;
double mass;
// ... some more stuff
};
body *bodies = malloc(Number_of_bodies*sizeof(body));
我需要知道数组的大小,所以我将大小存储在其中一个结构中,它位于数组的第 0 个元素(第一个结构)中。
bodies[0].mass = (double)Number_of_bodies;
然后我从函数返回一个指向数组第一个元素的指针,即 bodies[1]
return (bodies+1);
现在,当我在其他函数中使用这个指针时,数据应该从第 0 个元素开始。
body *new_bodies = (bodies+1); //Just trying to show what happens effectively when i pass to another function
new_bodies[0] = *(bodies+1); //I Think
如果我想查看位于 bodies[0]
的初始结构,这是否意味着在其他函数中我必须访问 new_bodies[-1]
?
这是我能做的吗? 如何访问初始结构?
最佳答案
是的,您可以使用new_bodies[-1]
来访问数组的初始元素。这是完全合法的。
这背后的原因是指针运算:方括号是+
的另一种写法,所以当你写new_bodies[-1]
时,它和是一样的>*(new_bodies-1)
。
由于new_bodies
已经获取为bodies+1
,new_bodies-1
为(bodies+1)-1
或 bodies
,使 new_bodies[-1]
与 bodies[0]
相同。
注意:看起来您正试图将元素数量硬塞进struct
数组的初始元素中,重新调整 mass
字段。这会起作用,但它不是最理想的,无论是在内存分配方面(指针 name
保持未使用状态)还是最重要的可读性方面。在显式存储条目数的 struct
中使用灵活的数组成员会好很多:
struct body {
char* name;
double mass;
// ... some more stuff
};
struct bodies {
size_t count;
body bodies[]; // <<== Flexible array member
};
...
bodies *bb = malloc(sizeof(bodies)+Number_of_bodies*sizeof(body));
bb->count = Number_of_bodies;
这里是 another Q&A with an example of working with flexible array members 的链接.
关于c - 在c中访问数组的-1元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26891438/