为什么使用malloc与结构? [英] why use malloc with structure?

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

问题描述

我为什么要使用malloc时,同样的工作,可以不用下面的malloc来完成。

 的#include<&stdio.h中GT;
#包括LT&;&CONIO.H GT;结构节点{
    int数据;
    结构节点* L;
    结构节点* R;
};诠释主(){
    //情况1
    结构节点N1;
    n1.data = 99;
    的printf(N1数据为%d \\ n,n1.data);    //案例2
    结构节点* N2 =(结构节点*)malloc的(的sizeof(结构节点));
    N2 - >数据= 4444;
    的printf(N2数据数:%d \\ n,N2 - >数据);
    免费(N2);    返回(0);
}


  1. 我有很难理解如何N1未初始化的内存位置能够存储数据(99)。

  2. 何时使用情况1,何时使用情况2.结果


解决方案

  

我为什么要使用malloc时,同样的工作,由甘蔗没有malloc的完成为
  下面..


您使用malloc,分配上的堆内存,没有malloc的,你把你的结构堆栈存储器。


  

我有很难理解如何N1未初始化
  到存储器位置是能够存储数据(99)。


初​​始化与否,当你指定数据 n1.data = 99; ,它存储


  

2)时使用的壳体1和何时使用情况下2


案例1时,当你知道你将要使用结构对象密闭的范围之内,并不会使得该结构数据引用,超出了它的范围。

第2种情况是,当你将使用你的结构在多个地方使用,你愿意为它手动管理内存(并仔细!)。这种方法的优点是,创建并在程序的范围的某部分初始化结构,并创建一个指针和周围传递指针,因为传递一个4字节的指针比更为有效,传递结​​构本身。

Why would I use malloc when same job can be done by without malloc as below..

#include <stdio.h>
#include <conio.h>

struct node {
    int data;
    struct node *l;
    struct node *r;
};

int main(){
    //Case 1
    struct node n1;
    n1.data = 99;
    printf("n1 data is %d\n", n1.data);

    //Case 2
    struct node *n2 = (struct node *) malloc (sizeof(struct node));
    n2 -> data = 4444;
    printf("n2 data is:%d\n",n2 -> data);
    free(n2);

    return (0);
}

  1. I am having hard time to understand how n1 which is not initialized to memory location is able to store data (99) .
  2. when to use case 1 and when to use case 2.

解决方案

Why would I use malloc when same job cane be done by without malloc as below..

You use malloc, to allocate memory on heap, and without malloc, you are placing you struct in stack memory.

I am having hard time to understand how n1 which is not initialized to memory location is able to store data (99) .

Initialized or not, when you assign data n1.data = 99; , it is stored.

2) when to use case 1 and when to use case 2

Case 1 is is used, when you know that you will be using the structure object within a confined scope, and will not be making references to the structure data, beyond its scope.

Case 2 is used when you will be using your structure at multiple places, and you are willing to manage memory for it manually(and carefully!). The advantage of this method is that, you create and initialize the structure at some part of the program scope, and you create a pointer and pass the pointer around, since passing a 4 byte pointer is far more efficient than , passing the structure itself.

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

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