指向结构的指针的大小 [英] Size of a pointer pointing to a structure
问题描述
我试图记住C编程的基础知识,关于结构的指针,我正在做以下事情:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main()
{
struct MyStruct {
int number;
char *name;
};
int i;
struct MyStruct *p_struct = (struct MyStruct *) malloc (sizeof(struct MyStruct)*3);
printf("sizeof(struct MyStruct) = %d\n", sizeof(struct MyStruct));
for (i=0; i<3;i++)
{
(*p_struct).number = i;
(*p_struct).name = "string";
printf("(*p_struct).number = %d, (*p_struct).name = %s\n", (*p_struct).number (*p_struct).name);
++p_struct;
}
printf("sizeof(p_struct) = %d\n", sizeof(p_struct));
free (p_struct);
return 1;
}
我的问题是:我得到8个字节作为结构的大小,由于编译器的对齐/填充,我可以得到4 + 4 = 8个字节,但是为什么我要从sizeof(p_struct)
得到4个字节呢? /p>
我原本希望得到24(8字节x 3),为什么会这样呢?
如果这是正确的,我能以某种方式获得24字节的总分配大小吗?
谢谢.
否,结构的大小为8个字节,因为其中有两个4个字节的字段,请尝试打印sizeof(int)
和sizeof(char *)
并查看是否你自己.
对指针执行sizeof
时,始终会得到指针的大小,而不是指针指向的内容. (在标准C中)无法获取使用malloc
分配的内存大小.
还请注意,在更改指针时,代码中有 未定义的行为 p_struct
,因此它不再指向您的malloc
调用返回的内容.当您尝试free
该内存时,这会导致未定义的行为.
I was trying to remember the basics of C programming, and regarding pointers to structures I was doing the following:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main()
{
struct MyStruct {
int number;
char *name;
};
int i;
struct MyStruct *p_struct = (struct MyStruct *) malloc (sizeof(struct MyStruct)*3);
printf("sizeof(struct MyStruct) = %d\n", sizeof(struct MyStruct));
for (i=0; i<3;i++)
{
(*p_struct).number = i;
(*p_struct).name = "string";
printf("(*p_struct).number = %d, (*p_struct).name = %s\n", (*p_struct).number (*p_struct).name);
++p_struct;
}
printf("sizeof(p_struct) = %d\n", sizeof(p_struct));
free (p_struct);
return 1;
}
My question is: I get 8 bytes as the size of the structure, which is okay as 4+4 = 8 bytes due to alignment/padding of the compiler, but why do I get 4 bytes from sizeof(p_struct)
?
I was expecting to get 24 (8 bytes x 3), why is this so?
If this is correct, can I get the total allocated size of 24 bytes somehow?
Thanks.
No, the size of the structure is eight bytes because you have two four-byte fields in it, try printing sizeof(int)
and sizeof(char *)
and see for yourself.
When you do sizeof
of a pointer, you always gets the size of the pointer and never what it points to. There is no way (in standard C) to get the size of memory you have allocated with malloc
.
Also note that you have undefined behavior in your code, as you change the pointer p_struct
so it no longer points to what your malloc
call returned. This leads to the undefined behavior when you try to free
that memory.
这篇关于指向结构的指针的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!