#include <stdio.h>
struct student
{
int roll_no;
int mark;
struct student *p;
};
int main()
{
struct student *stu;
stu = malloc(sizeof(struct student));
}
对于结构类型,malloc()
的实际返回值是多少?它是如何分配给结构变量的?
现在来看语句,
struct student *stu;
内存分配就像4字节的stu
,假设从1000
开始。
和语句
stu = malloc(sizeof(struct student));
首先分配内存块,我们称其为2000
- 2012
。然后赋值部分指向存储在1000
中的2000
的指针.
这就是赋值部分对malloc()
和结构变量的工作方式。
现在是保存起始地址2000
的指针,即stu
。所以现在stu->roll_no
将访问前4个字节,stu->mark
将访问下4个字节,依此类推。问题是编译器如何理解它,不是stu->roll_no
等同于*(stu+0)
,stu->mark
等同于*(stu+1)
。对此的解释将非常感谢。
发布于 2019-06-03 01:10:56
malloc return void *指向您发送的内存中某一位置的指针,您可以将该指针转换为您想要的任何- https://www.tutorialspoint.com/cprogramming/c_type_casting.htm类型。请参阅malloc定义:https://www.tutorialspoint.com/c_standard_library/c_function_malloc.htm
https://stackoverflow.com/questions/56412211
复制相似问题