首页 > 解决方案 > 解释指针和 sizeof 结构的不同值

问题描述

我是新来的,我也是编程新手。我正在学习结构、指针和函数以及它们如何在 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)大小时为什么没有改变?我构建的这段代码让我对整体上什么是什么以及如何区分概念和其他概念更加困惑。很抱歉这个凌乱的长问题。再次这是我的第一次,所以请善待您的批评并彻底回答您的问题。谢谢。

标签: cfunctionpointersstructtypedef

解决方案


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 标准不要求不同类型的指针具有相同的大小——即使它很常见。您的系统似乎就是这种情况。


推荐阅读