【问题标题】:explaining the different values for pointers and sizeof struct解释指针和 sizeof 结构的不同值
【发布时间】:2018-10-31 04:53:43
【问题描述】:

我是新来的,我也是编程新手。我正在学习结构、指针和函数,以及它们如何在 C 中协同工作。我试图理解我从以下代码中得到的结果:

#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h> 
#include <ctype.h>
#include <string.h>

typedef struct {
  int* data;
  unsigned int len;
} intarr_t;

intarr_t* intarr_create( unsigned int len )
{
  intarr_t* parr= malloc(sizeof(intarr_t));
  parr->data= malloc(len*sizeof(int));
  parr->len= len;

  if (parr->data && parr)
    return parr;
  else
    return NULL;
}

int main()
{ 
  intarr_t* p = intarr_create(3); //creat a typedef struct "intarr_t" with data pointer that has 3 integer values allocate to it.
  printf("%ld %ld %ld %ld %ld %ld %ld\n",sizeof(p), sizeof(*p), sizeof(*(p->data)), sizeof(p->data), sizeof(*(&(p->data))), sizeof(&(p->data)), sizeof(p->data[0]));
  printf("%p %p %p %p %p\n", (void*)p, (void*)p->data, (void*)&(p->len), (void*)&(p->data), (void*)&(p->data[0]));
  intarr_destroy(p);
}

我得到的输出与我设置的“len”相同。

8 16 4 8 8 8 4
0x55f672e0c260 0x55f672e0c280 0x55f672e0c268 0x55f672e0c260 0x55f672e0c280

有人可以解释一下代码中的每一个结果和相应的部分吗?哪一个引用指针,数据指针和数据中的值,每个指针的解引用?为什么尺寸是它们的结果?为什么每个选项中地址数据的大小都会改变,当我改变多少元素(len)大小时为什么没有改变? 我构建的这段代码让我对整体上什么是什么以及如何区分概念和其他概念更加困惑。 很抱歉这个凌乱的长问题。再次这是我的第一次,所以请善待您的批评并彻底回答您的问题。谢谢。

【问题讨论】:

  • 附注sizeof(int)=4 和 sizeof(unsighed int)=4 在我的机器上。
  • 旁白:在if (parr-&gt;data &amp;&amp; parr) 中对parrNULL-ness 的测试为时已晚,无法使用。应该就在intarr_t* parr= malloc(...之后
  • 具体来说,8 16 4 8 8 8 4 上的哪些值是您意想不到的?您期望什么值?
  • 顺便说一句,在分配给parr-&gt;dataparr-&gt;len 之前,您确实需要检查parr 是否为空。

标签: c function pointers struct typedef


【解决方案1】:
8 - sizeof(p) - size of a pointer to struct inarr_t which is the same as size of any pointer 
16 - sizeof(*p) - size of struct inarr_t consisting of an int and a pointer with padding 
4 - sizeof(*(p->data)) - size of int
8 - sizeof(p->data) - size of pointer to int which is the same as size of any pointer 

8 - sizeof(*(&(p->data))) - size of pointer to int (*& is dereferencing a pointer to pointer) 
8 - sizeof(&(p->data)) - size of pointer to pointer to int
4 - sizeof(p->data[0])) - size of int (the first element of int array)

不管len的大小是多少,上面的值都不会改变。

注意:C 标准不要求不同类型的指针具有相同的大小——即使它很常见。您的系统上似乎就是这种情况。

【讨论】:

  • "...这与任何指针的大小相同" --> C 并不要求不同类型的指针都具有相同的大小——即使它很常见。当指向函数的指针与指向对象的指针大小不同时,就会出现典型的差异。
  • @chux:用您的输入更新了答案。
猜你喜欢
  • 2021-04-21
  • 1970-01-01
  • 2023-03-21
  • 2021-03-28
  • 2020-08-29
  • 2020-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多