算法的阶梯

C:malloc function

2018-08-22  本文已影响9人  Tedisaname
malloc is a function in C, how to understand and use it, just following the next example.
examp1:
//malloc is an abbreviation word,is made of word memeroy and allocate 
#include <stdio.h>
#include <malloc.h> 
int main()
{
    int i = 5;//allocate 4 bytes    static allocation 
    int * p = (int *)malloc(4);
    /*
    1、u must add the header file to ur codes if 
     u want to use the malloc function
    2、malloc function only has one  parameter and it mube be a int type
    3、4 means ask the system to allocate 4 bytes for this program
    4、only the address of the first bytes can be returned to the malloc function 
    5、the seventh line totally allocates 8 bytes, the variable of p
     occupies 4 bytes and the variable of p points to the memroty part also 
     holds 4 bytes
    6、the allocation of p is allocated in a static way,
        the part of p is allocated in a dynamic way.
    */
    *p = 5;  //give value with 5
    free(p);
    return 0;
}
The above procedure has no special meanings, just a example to make u understand it.
exmp2:
#include <stdio.h>
#include <malloc.h>
void f(int *q)
{
    //*p = 200;//error
    //q = 200;//error
    //**q = 200;error
    *q = 200;
    //free(q);//release the memrory of the variable q
}
int main()
{
    int *p = (int *)malloc(sizeof(int));
    *p = 10;
    printf("%d\n",*p);//10
    f(p);
    printf("%d\n",*p);//200
    return 0;
}
//results:
10
200   //the value of the variable of p has already changed
//Attention:the static variable can not be free, 
//only the dynamic variable can be manually free  by the programmer
上一篇下一篇

猜你喜欢

热点阅读