malloc/free 的使用要点

函数 malloc 的原型如下: void * malloc(size_t size); 用 malloc 申请一块长度为 length 的整数类型的内存,程序如下: int *p = (int *) malloc(sizeof(int) * length);

我们应当把注意力集中在两个要素上:“类型转换”和“sizeof”。

 malloc 返回值的类型是 void *,所以在调用 malloc 时要显式地进行类型转换,将 void * 转换成所需要的指针类型。

malloc 函数本身并不识别要申请的内存是什么类型,它只关心内存的总字节数。我 们通常记不住 int, float 等数据类型的变量的确切字节数。例如 int 变量在 16 位系统 下是 2 个字节,在 32 位下是 4 个字节;而 float 变量在 16 位系统下是 4 个字节,在 32 位下也是 4 个字节。

 1 #include <iostream>
 2 
 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 4 using namespace std;
 5 int main(int argc, char** argv) {
 6         //声明数组、变量和指针变量
 7     int a[2][3],i,j;
 8     int* ip;
 9 
10     //从键盘上为数组a赋值
11     for (i=0;i<2;i++)  //为数组a赋值
12         for (j=0;j<3;j++) 
13         {
14            cout<<"a["<<i<<"]["<<j<<"]=";
15            cin>>a[i][j];
16          }
17 
18     //利用下标变量显示数组a
19     for (i=0;i<2;i++) { 
20         for (j=0;j<3;j++) 
21         {
22            cout<<a[i][j]<<"  ";
23         }
24         cout<<endl;
25     }
26 
27     //利用指针变量显示数组a
28     ip=&a[0][0];     
29     for (i=0;i<2;i++) { 
30          for (j=0;j<3;j++) 
31          {
32             cout<<"a["<<i<<"]["<<j<<"]=";
33             cout<<ip<<"  ";
34             cout<<*ip<<endl;
35             ip++;
36          }
37     }
38     return 0;
39 }
原文地址:https://www.cnblogs.com/borter/p/9406462.html