c - 解释指针和 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)大小时为什么没有改变?我构建的这段代码让我对整体上什么是什么以及如何区分概念和其他概念更加困惑。很抱歉这个凌乱的长问题。再次这是我的第一次,所以请善待您的批评并彻底回答您的问题。谢谢。
解决方案
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 标准不要求不同类型的指针具有相同的大小——即使它很常见。您的系统似乎就是这种情况。
推荐阅读
- php - 将 2 个集合数据与 mongodb 和 php 中的排序和分页结合起来
- java - Java中的线程可以缓存最终字段吗?
- bash - 将 awk(索引搜索)输出保存在 shell 变量中(返回值除外)
- html - CSS显示错误
- typescript - 插入到全局变量中的值不能在函数外使用
- sql - PostgreSQL - 每年任何给定月份有多少活跃客户?
- android - 使用 Lets Encrypt SSL 证书和交叉 WAMP 路由器 (0.13)
- python - 带有标签 docker_login 错误的 Jenkins ansible-playbook
- javascript - 如何在后台运行繁重的程序时显示“正在计算”消息以防止滞后
- blockchain - 即使在 seth-cli-go 中创建了别名,Seth-rpc 错误“在密钥目录中找不到别名”