我有一个球,它有一个相邻的球,如下面的代码所示。我面临的问题是更新存储在ball 1的相邻区域中的ball 2值,而不是更新实际的ball 2。
struct ball {
struct ball * adjacent;
size_t n_adjacent;
};
// Setting ball 2
struct ball ball2 = { .n_adjacent= 0, .adjacent = NULL } ;
// setting ball 1
struct ball ball1 = { .n_adjacent= 1, .adjacent = NULL } ;
// setting ball 1's adjacent
struct ball * ball1_adj = (struct ball*) calloc(1, sizeof(struct ball));
ball1_adj[0] = ball2;
ball1.adjacent = ball1_adj;
printf("Address of original ball 2 is: %pn", &ball2);
printf("Address of ball 2 in the array is: %pn", &(ball1.adjacent[0]));
// different but Ok as malloc has returned a pointer
ball1.adjacent[0].n_adjacent = 10; // Updating ball 2 's adjacents
printf("Adjacent of original ball 2 is: %dn", ball2.n_adjacent); // prints 0
printf("Adjacent of ball 2 in the array is: %dn", (ball1.adjacent[0]).n_adjacent); // prints 10
- 是否为ball2和ball1。是否相邻[0]同一个球(ball2(
- 为什么ball2的值没有更新
感谢
是否是ball2和ball1。是否相邻[0]同一个球(ball2(?
否。您制作ball2
的副本并将其存储在ball1_adj[0]
中,然后将该副本的地址分配给ball1.adjacent
为什么ball2的值没有更新?
因为修改副本不会影响该副本的来源。就像焚烧你的汽车照片不会损坏你的汽车一样。
如果您想使用adjacent
指针修改其他结构,则需要分配其他结构的地址,而不是副本:
ball1.adjacent = ball1_adj;
=> ball1.adjacent = &ball2;