1

我有 2 个结构:

struct b{int b;float d;}; and 
struct a{int count; struct b* ptr;}
struct a *a_temp;

现在我为 10 个 b 类型的结构分配内存,并将地址放在结构 a 的 ptr 中。(代码给了我,他们出于某种原因不想使用双指针)

a_temp = (struct a*)malloc(sizeof(struct a));
a_temp->ptr = (struct b*)malloc(10*sizeof(struct b));
struct b* b_temp;

我必须将 b 类型的第二个结构的地址加载到 temp_b。我尝试b_temp = a_temp->ptr[1];了哪个给出错误,但是b_temp = &(a_temp->ptr[1]);当我尝试使用它并使用它访问结构 b 的内容时它正在工作,这是为什么呢?

提前致谢

4

1 回答 1

3

ptr[1]is 结构,由ptr + 1(就像*(ptr+1))所指向,b_temp得到一个指向结构的指针,所以你必须传递 的地址a_temp->ptr[1],即&a_temp->ptr[1]

expression      | type
---------------------------
a_temp->ptr     | struct b*
a_temp->ptr[1]  | struct b
&a_temp->ptr[1] | struct b*
a_temp->ptr + 1 | struct b*
b_temp          | struct b*

编辑:

如果您有一个指针,可以说int * x,那么以下表达式是相同的:x[1]and *(x+1),并且它们都遵循 address x+1。换句话说,这些表达式 value 是指针x指向的变量的类型,在这种情况下它是 an int,因为xis int *(pointer to int) 它保存了一个变量的地址。int

于 2011-11-01T12:00:16.383 回答