malloc 函数本身并不识别要申请的内存是什么类型

 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 //在main()函数中测试display函数模板
 5 using namespace std;
 6 //函数模板的原型
 7 
 8 
 9 int main(int argc, char** argv) {
10       //声明变量
11     char c='A';
12     char str[]="This is a test";
13     int n=10;
14     float x=1.5;
15     double z=3.1415926;
16 
17     //两个参数类型相同
18     display(c, char(c+2));
19     display(str, str);
20     display(n, 2*n);
21     display(x,2*x);
22     display(z, 2*z);
23     cout<<"------------------"<<endl;
24 
25     //两个参数类型不同
26     display(c, str);
27     display(str, c);
28     display(n, str);
29     display(str,2*x);
30     display(z, n);
31     return 0;
32 }
33 template <class T1, class T2> void display(T1 x, T2 y);
34 
35 
36 
37 
38 //定义名为display的函数模板
39 template <class T1, class T2> void display(T1 x, T2 y)
40 {
41     cout << x << " " << y << endl;

 

posted @ 2018-08-03 13:43  borter  阅读(271)  评论(0编辑  收藏  举报