简体   繁体   English

结构体中的指针大小

[英]Size of pointer inside a struct

So, I have this structure used to implement a circular buffer of another structure ( plane ) 因此,我使用了此结构来实现另一个结构( plane )的循环缓冲区

typedef struct queue
{
    struct plane *q;        
    int size, capacity, front, rear;  
}queue;

After this I declare the structure 在此之后,我声明结构

queue *q;

and later, to inicialize the buffer, I use this method 稍后,为了初始化缓冲区,我使用了这种方法

int queue_init(int size){

    q = (queue*) malloc(sizeof(queue));

    q->q=malloc(sizeof(struct plane) * size); 

    q->size = 0;
    q->capacity = size;
    q->front = 0;
    q->rear = 0;

    return 0;
}

which is supposed to be the one that inicializes all the variables I need to use the buffer and the buffer itself with q->q=malloc(sizeof(struct plane) * size); 这应该是初始化所有我需要使用的变量的缓冲区和q->q=malloc(sizeof(struct plane) * size);的缓冲区本身q->q=malloc(sizeof(struct plane) * size); . The problem is the size of the buffer is always 8 bytes, where it should be as it says, size times the size of plane , which is actually 16. The thing is how should I initialize the variables so I can get the buffer the size I want. 问题是缓冲区的大小始终是8个字节,它应该是因为它说, size的倍大小plane ,这实际上是16的事情是我应该如何初始化变量,这样我就可以得到缓冲大小我想要。 I can't change the return value or the parameters of the function as limitations. 我不能更改返回值或函数的参数作为限制。 Thank you beforehand! 预先谢谢你!

If you're trying to get the size of the array by doing sizeof(q->q) , this won't work as you expect. 如果您尝试通过执行sizeof(q->q)来获取数组的大小,那么这将无法按预期工作。

Since the q field of struct queue is a pointer and not an array, sizeof(q->q) actually gives you the size of the pointer which on your machine appears to be 8 bytes in size. 由于struct queueq字段是指针而不是数组,因此sizeof(q->q)实际上为您提供了指针的大小,该指针在您的计算机上看起来是8个字节。

The language doesn't keep track of how much memory was allocated in a call to malloc , so you need to keep track of that yourself. 该语言无法跟踪对malloc的调用中分配了多少内存,因此您需要自己跟踪。 The good thing is that you're already doing that. 好消息是您已经在这样做了。

You correctly allocated room for an array of struct place of size size by using malloc(sizeof(struct plane) * size) , and you stored size in q->capacity . 您正确分配空间的数组struct place大小的size使用malloc(sizeof(struct plane) * size) ,以及你存储sizeq->capacity So you know how big the array is. 因此,您知道阵列的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM