【问题标题】:pointer of unsigned char array and his pointer has the same value, why?unsigned char数组的指针和他的指针有相同的值,为什么?
【发布时间】:2021-04-17 13:49:28
【问题描述】:

我注意到一种我无法解释的行为。 `

typedef unsigned char mac_address_t[6];
mac_address_t* c = malloc(sizeof(mac_address_t)); 
printf("%p \n", c); 
printf("%p \n", (*c));`

打印的值是一样的。 另一种打印值的方法是

printf("%p \n", &(*c)[0]); 

不过这个我能理解,先start访问数组,然后[]访问数组的元素。在这种情况下,我无法理解 c 和 *c 背后的逻辑。此外,如果值相同,为什么我不能 c[i] 访问元素? 有人可以帮助我吗?

【问题讨论】:

  • 不要 typedef 数组类型,以免造成混淆。像这样的 Typedef 是非常糟糕的做法,您只是发现了许多原因之一。

标签: arrays c pointers memory


【解决方案1】:

c 是一个指向数组的指针。

*c是指针c指向的数组。

表达式中的数组被转换为指向数组第一个元素的指针。 (存在一些例外情况)。

因此*c 被转换为指向数组第一个元素的指针。

通常数组的起点和数组的第一个元素的起点是相同的。

这就是c*c 具有相同地址的原因。

&(*c)[0] 明确表示“数组*c的第一个元素的地址”,与*c转换后的内容相同。

c是指向数组的指针,所以c[i]得到的是数组,而不是数组的元素。

【讨论】:

    【解决方案2】:

    这是因为您的mac_address_t typedef 在技术上是一个字符数组,它在内部是一个指向相邻字符集合的指针。因此,当您使用mac_address_t* c = malloc(sizeof(mac_address_t)); 创建指向此类型的指针时,您实际上创建了指向指针的指针。在这种情况下,取消引用第一个指针只是获得第二个指针的地址。这可以通过使用相同的示例和未定义数组的简单 typedef 来看出。

    在下面的示例中,test_t 具有您可能期望的行为,而 mac_address_t 具有您注意到的特征。

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argv, char* argc[], char* argp[]){
    
      typedef unsigned char mac_address_t[6];
      typedef unsigned char test_t;
    
      mac_address_t* c = malloc(sizeof(mac_address_t));
      printf("%p \n", c);
      printf("%p \n", (*c));
    
      test_t* t = malloc(sizeof(test_t));
      printf("%p \n", t);
      printf("%p \n", (*t));
    
      return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-03-02
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2016-12-02
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多