什么时候以及为什么要使用malloc? [英] When and why to use malloc?

查看:861
本文介绍了什么时候以及为什么要使用malloc?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我不明白何时和为什么需要使用malloc分配内存.

Well, I can't understand when and why it is needed to allocate memory using malloc.

这是我的代码:

#include <stdlib.h>

int main(int argc, const char *argv[]) {

  typedef struct {
    char *name;
    char *sex;
    int age;
  } student;


  //Now I can do two things
  student p;

  //or
  student *ptr = (student *)malloc(sizeof(student));

  return 0;
}

为什么我只能使用student p;时需要分配内存?

Why is it needed to allocate memory when I can just use student p;?

推荐答案

malloc用于动态内存分配.如前所述,它是动态分配,这意味着您可以在运行时分配内存.例如,当您在编译时不知道内存量时.

malloc is used for dynamic memory allocation. As said, it is dynamic allocation which means you allocate the memory at run time. For example when you don't know the amount of memory during compile time.

一个例子应该清除这一点.假设您知道最多会有20名学生.因此,您可以创建一个包含20个静态元素的数组.您的阵列最多可容纳20名学生.但是,如果您不知道学生人数怎么办?说第一个输入是学生人数.可以是10、20、50或其他任何值.现在,您将输入n =运行时的学生人数,并使用malloc动态分配那么多内存.

One example should clear this. Say you know there will be maximum 20 students. So you can create an array with static 20 elements. Your array will be able to hold maximum 20 students. But what if you don't know the number of students? Say the first input is the number of students. It could be 10, 20, 50 or whatever else. Now you will take input n = the number of students at run time and allocate that much memory dynamically using malloc.

这只是一个例子.在许多情况下,需要动态分配.

This is just one example. There are many situations like this where dynamic allocation is needed.

看看手册页 malloc(3).

这篇关于什么时候以及为什么要使用malloc?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆