首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >结构类型的malloc()返回值

结构类型的malloc()返回值
EN

Stack Overflow用户
提问于 2019-06-02 12:30:19
回答 1查看 162关注 0票数 -3
代码语言:javascript
复制
#include <stdio.h>

struct student
{
  int roll_no;
  int mark;
  struct student *p;
};

int main()
{
  struct student *stu;
  stu = malloc(sizeof(struct student));
}

对于结构类型,malloc()的实际返回值是多少?它是如何分配给结构变量的?

现在来看语句,

代码语言:javascript
复制
struct student *stu;

内存分配就像4字节的stu,假设从1000开始。

和语句

代码语言:javascript
复制
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)。对此的解释将非常感谢。

EN

回答 1

Stack Overflow用户

发布于 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

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56412211

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档