下面的代码
//gcc 5.4.0
#include <stdio.h>
#include <string.h>
#include <assert.h>
struct a{
int a;
};
void change(struct a * a) {
a->a = 5;
}
int main(void)
{
struct a * a = malloc(4*sizeof(struct a));
a[3].a = 2;
assert(a[3].a == 2);
change(&a[3]);
assert(a[3].a == 5);
printf("Hello, world!\n");
return 0;
}
为什么 change(&a[3]);
不传递 change(&a);
或 change(a);
本身的地址因为 a[3] 的地址不就是 a 本身吗?
例如
a = 指针
3 = 指针的索引 3
a[3] = 索引 3 处的结构
&a[3] = 结构体的地址 > a 的地址,根据 struct a * a,a 指向结构体 a,并且 a[3] 是从 a 到第三个结构体(该结构体的父级)的指针第三个结构是它本身
最佳答案
您的代码中有许多a
。
- 结构体类型
a
- 该结构体的一个元素,它是一个整数
a
- main 中指向此结构
a
的指针。指针的名称也是a
这确实不是一个好方法,但这是每行的解释。
struct a * a = malloc(4*sizeof(struct a)); // Allocate memory to a (no 3) (pointer) of 4 structures . (i.e. 4 structures)
a[3].a = 2; //the third structure's element (a) has value 2.
assert(a[3].a == 2); // Check
change(&a[3]); // Pass the address of a[3] (third element of structure array to function
// Function will change the element a of a[3] to 5
assert(a[3].a == 5); // verify that a[3].a == 5
printf("Hello, world!\n");
return 0;
关于c - &A[1] 应该与 A 本身的地址相同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52752156/