本文学习自 狄泰软件学院 唐佐林老师的 C++课程
-
在C语言中,是通过一个库函数 malloc()来完成动态内存分配的,C语言本身不支持动态内存分配,C++中增加了new关键字进行动态内存申请
-
C中只有一个全局作用域,所有的标识符共享一个全局作用域,标识符之间可能会产生冲突。由此C++提出来作用的概念
实验1:C++中的动态内存分配
实验2:初始化动态内存(堆空间)
实验3:命名空间的使用
实验1:C++中的动态内存分配
#include <stdio.h>
int main()
{
int* p = new int;
*p = 5;
*p = *p + 10;
printf("p = %p\n", p);
printf("*p = %d\n", *p);
delete p;
p = new int[10];
for(int i=0; i<10; i++)
{
p[i] = i + 1;
printf("p[%d] = %d\n", i, p[i]);
}
delete[] p;
return 0;
}
mhr@ubuntu:~/work/c++$ g++ 10-1.cpp
mhr@ubuntu:~/work/c++$ ./a.out
p = 0x23dfc20
*p = 15
p[0] = 1
p[1] = 2
p[2] = 3
p[3] = 4
p[4] = 5
p[5] = 6
p[6] = 7
p[7] = 8
p[8] = 9
p[9] = 10
mhr@ubuntu:~/work/c++$
问题: p = new int[10]; 此处所申请的内存空间的大小是多少?
答案: 动态申请出来的空间会比实际需要的多一点。这里的问题的答案是 至少40个字节。
实验2:初始化动态内存(堆空间)
#include <stdio.h>
int main()
{
int* pi = new int(1);
// int* pa = new int[1];
float* pf = new float(2.0f);
char* pc = new char('c');
printf("*pi = %d\n", *pi);
printf("*pf = %f\n", *pf);
printf("*pc = %c\n", *pc);
delete pi;
delete pf;
delete pc;
return 0;
}
mhr@ubuntu:~/work/c++$ g++ 10-2.cpp
mhr@ubuntu:~/work/c++$ ./a.out
*pi = 1
*pf = 2.000000
*pc = c
mhr@ubuntu:~/work/c++$
实验3:命名空间的使用
#include <stdio.h>
namespace First
{
int i = 0;
}
namespace Second
{
int i = 1;
namespace Internal
{
struct P
{
int x;
int y;
};
}
}
int main()
{
//我们将要在 main()中使用 First 这个命名空间中的一切资源
using namespace First;
//我们将要在 main()中使用 Second命名空间中的Internal命名空间中的P这个标识符
using Second::Internal::P;
//直接通过名字访问i ,因为前面已经 提出了要使用 First 这个命名空间中的一切资源
printf("First::i = %d\n", i);
//通过 Second::i 访问 Second命名空间中的i
printf("Second::i = %d\n", Second::i);
P p = {2, 3};
printf("p.x = %d\n", p.x);
printf("p.y = %d\n", p.y);
return 0;
}
mhr@ubuntu:~/work/c++$ g++ 10-3.cpp
mhr@ubuntu:~/work/c++$ ./a.out
First::i = 0
Second::i = 1
p.x = 2
p.y = 3
mhr@ubuntu:~/work/c++$