如何做一个结构数组里面工作? [英] How do arrays work inside a struct?

查看:135
本文介绍了如何做一个结构数组里面工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有例如:

typedef struct node
{
    int numbers[5];
} node;

每当我建立这样一个结构的实例有会是的内存分​​配在堆栈中的数组本身,(在我们的情况下,20个字节的5个整数(考虑整数为32位)),和数字是会是一个指针,该缓存器的第一个字节。所以,我想,既然节点的实例中,有会是一个20字节的缓冲区(为5 INT S)和一个4字节的指针(数字),的sizeof(节点)应该是24个字节。但是当我真正把它打印出来就是说,20个字节。结果这究竟是为什么?为什么指针数组没有考虑到?
结果我应当承担任何反应非常感激。

Whenever I create an instance of such a struct there's gonna be allocation of memory in the stack for the array itself, (in our case 20 bytes for 5 ints(considering ints as 32 bits)), and numbers is gonna be a pointer to the first byte of that buffer. So, I thought that since inside an instance of node, there's gonna be a 20 bytes buffer(for the 5 ints) and a 4 bytes pointer(numbers), sizeof(node) should be 24 bytes. But when I actually print it out is says 20 bytes.
Why is this happening? Why is the pointer to the array not taken into account?
I shall be very grateful for any response.

推荐答案

数组不是指针:


  • INT改编[10]


  • 所使用的内存量的sizeof(int)的* 10 字节

的改编&安培值; ARR 必然是相同的。

改编指向一个有效的内存地址,但不能设置为指向另一内存地​​址

arr points to a valid memory address, but cannot be set to point to another memory address


  • 为int * PTR =的malloc(sizeof的(INT)* 10)


  • 所使用的内存量的sizeof(INT *)+的sizeof(INT)* 10 字节

的值 PTR &放大器; PTR 不一定是相同的(事实上,他们是大多是不同的)

The values of ptr and &ptr are not necessarily identical (in fact, they are mostly different)

PTR 可设置为指向有效和无效的内存地址,多次随你便

ptr can be set to point to both valid and invalid memory addresses, as many times as you will

这篇关于如何做一个结构数组里面工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆