malloc如何在C中运行 [英] How malloc works in C

查看:61
本文介绍了malloc如何在C中运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

malloc的基本语法就像是

a =(int *)malloc(n * sizeof(int);

我想问这个实际上是什么意思和为什么我们有一个*

而另一件事是做一个2d数组动态分配我们必须使用

a =(int **)malloc(n * sizeof(int *);

为什么我们有2 *这里



我尝试了什么:



查看不同的网站,我甚至尝试从某些代码中删除它们但无论如何它们仍在工作

解决方案

int *表示指向整数的指针。星号表示指针语法。在声明中是指向类型的指针。在语句中,它表示指针被解引用,因此您获得它指向的值。



双星号表示指向指针的指针。表达式只是动态分配2D数组所需工作的一部分。为行指针分配空间,现在需要分配数据本身。通常这样做:

  int  **  array  =(< span class =code-keyword> int  **)calloc(n, sizeof  int  *)); 
for (i = 0 ; i< n; ++ n)
{
array [i] = calloc(n, sizeof int ));
}

这将分配一个n乘二维的整数数组。我使用calloc因为它会自动为你存储内存。您必须反转操作才能完全释放内存。这意味着循环遍历每一个以释放行数据,然后一个调用释放行指针:

 for(i = 0; i< n; ++ n)
{
free(array [i]);
}
free(array);


malloc分配一个内存块,其中包含从系统获取的请求大小。返回的值是指向内存的指针。将其理解为内存块的起点。你的代码必须根据需要整理这个内存。



我更喜欢新的并尽可能删除。



您可以使用调试器和进入malloc 来查看其内部工作方式。 关于malloc 的精彩内容。

The basic syntax of malloc is like
a = (int*) malloc(n * sizeof(int);
I wanted to ask what this ints mean actually and why do we have a *
and another thing is to make a 2d array dynamic allocation we have to use
a = (int**) malloc(n * sizeof(int*);
why do we have 2 * here

What I have tried:

Looking in diffrent sites and i even tried deleting them from some codes but they worked anyway

解决方案

int * means a pointer to an integer. The asterisk signifies pointer syntax. In a declaration that is a pointer to a type. In a statement it means the pointer is dereferenced so you obtain the value it points to.

The double asterisk means a pointer to a pointer. Your expression is only part of the work required to allocate a 2D array dynamically. That allocated the space for the row pointers and now you need to allocate the data itself. Typically that is done like this :

int ** array = (int **)calloc( n, sizeof(int *) );
for( i = 0; i < n; ++n )
{
   array[i] = calloc( n, sizeof( int ) );
}

That will allocate an n by n two dimensional array of integers. I use calloc because it automatically zeros out the memory for you. You will have to reverse the operations to fully release the memory. That means looping through each one to free the row data and then one call to free the row pointers :

for( i = 0; i < n; ++n )
{
   free( array[i] );
}
free( array );


malloc allocates a memory block with the request size which it gets from the system. The returned value is the pointer to the memory. Understand it as starting point of the memory chunk. Your code must intepret this memory as you want.

I prefer new and delete when possible.

You can use the debugger and step into malloc to see its inner workings. A nice articel about malloc.


这篇关于malloc如何在C中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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