【问题标题】:should &A[1] be the same address as A itself?&A[1] 应该与 A 本身的地址相同吗?
【发布时间】:2018-10-11 04:21:23
【问题描述】:

以下代码

//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(&amp;a[3]); 不传递change(&amp;a);change(a); 本身的地址,因为a[3] 的地址不只是一个本身?

例如

a = 指针

3 = 指针的索引 3

a[3] = 索引 3 处的结构

&a[3] = 结构体的地址 > a 的地址,根据结构体 a * a,a 指向结构体 a,因为 a[3] 是从 a 指向第三个结构体的指针,即第三个结构是一个本身

【问题讨论】:

  • a == &amp;a[0]&amp;a[3] == (a+3).
  • &amp;a[3] 是指向“数组”a 中第四个元素的指针。
  • 埃加德。 a 的含义太多了。
  • 所以&amp;a[3]是数组a索引3处的结构地址?
  • @aschepler aaaaaaaaaaa!

标签: c pointers memory-address


【解决方案1】:

您的代码中有许多a

  1. 结构类型a
  2. 此结构的一个元素,它是一个整数a
  3. 指向此结构 a 在 main 中的指针。指针名称也是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;

【讨论】:

    【解决方案2】:

    您应该按照@Rishikesh 的建议使用良好的编程实践,看看Wkipedia 中的article

    但是,无论如何,正如@aschelper 所说,&amp;a[3] 是数组的第四个元素的地址。

    这是因为precedence of the operators[] 运算符比 &amp; 运算符具有更高的优先级,因此 C 首先获取数组的第四个(索引 3)元素,然后返回它的地址。

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 2013-12-25
      • 1970-01-01
      • 2013-08-24
      • 2021-06-10
      • 1970-01-01
      • 2017-01-30
      • 2014-07-24
      • 1970-01-01
      相关资源
      最近更新 更多