指针-转换为结构指针+ Malloc [英] Pointers - Casting as Struct Pointer + Malloc
问题描述
我对此有一些想法,但是我想要一个更专业和更有经验的解释.
I have some ideas of what this would do, but I'd like a more professional and experienced explaination.
typedef struct{
char str[50];
unsigned short num;
}s;
s *name = (s *) malloc(sizeof(s));
第一部分定义一个结构.我没问题
这将创建一个指向"s"结构的指针. malloc()
返回一个内存地址,该地址将被转换为指向"s"的指针.但是,sizeof(s)
我相信我在理解某些问题.
char str[50];
= 50个字节.
unsigned short num;
= 2个字节.
The first part defines a struct. I have no problem with that
This will create a pointer to "s" struct. malloc()
returns a memory address that will be cast as a pointer to "s". However, sizeof(s)
I Believe I am having some issues understanding.
char str[50];
= 50 bytes.
unsigned short num;
= 2 bytes.
sizeof(s)返回52个字节?
malloc(sizeof(s))
分配52个字节并返回第一个地址并将其转换为指向"s"的指针?
sizeof(s) returns 52 bytes?
malloc(sizeof(s))
allocates 52 bytes and returns the first address and casts it as a pointer to "s"?
还有一个问题! 如何使用内联malloc执行错误处理?
One More Question! How can I perform error handling with malloc in-line?
感谢任何可以帮助您澄清这一点的人!
Thanks to anyone that can help clarify this!
推荐答案
- 在C语言中,我们不需要强制转换
malloc
的返回值. malloc返回void *,在C语言中,void *隐式转换为您指定的任何类型... -
sizeof(s)
返回的值取决于填充以及实现(cos,sizeof(unsigned short)
在不同平台上会有所不同...). -
在C中,如果要检查错误,则必须将
malloc
的返回值与NULL
进行比较.- In C, we need not cast the return value of
malloc
. malloc returns void* and in C, void* implicitly cast to whatever type you specify... - The value returned by
sizeof(s)
depends on padding and also on the implementation (cos,sizeof(unsigned short)
will be different on different platforms...). In C, if you want to check for the error, you have to compare the return value of
malloc
withNULL
.如果(name == NULL)退出(1); //EXIT_FAILURE
if (name ==NULL) exit (1); //EXIT_FAILURE
这篇关于指针-转换为结构指针+ Malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- In C, we need not cast the return value of