目录
一.内存结构
二.内存拷贝函数
三.栈空间与堆空间
四.变量的四种存储类型
五.函数返回值使用指针
六.常见错误总结
- 个人主页:北·海
- CSDN新晋作者
- 欢迎 点赞✍评论⭐收藏
- ✨收录专栏:C/C++
- 希望作者的文章能对你有所帮助,有不足的地方请在评论区留言指正,大家一起学习交流!
//字符串常量
char* p = "你好";
char* p1 = "你好";
#include
#include "标头.h"//存放了文件2里面函数的声明
using namespace std;
static int d = 40;
//register int c = 30;//error 不能声明为全局
auto b = 20;
int value = 40;
//extern int e ;//error
extern int e = 20;//success
int main() {
auto a = 10;
e = 30;
cout << e << endl;
{
main1();//其他文件
static int f = 30;//success
register int g = 30;//success
auto h = 30;//success
//auto int i = 30;//error 在c++中不能定义为auto int 应该省略掉int,c语言中可以定义为auto int
}
//cout << f << endl;error 块内定义的
}
//文件2
#include
using namespace std;
extern int b;
extern int value;
int main1() {
cout <<"b :"<< b << endl;
cout << "value :" << value << endl;
return 0;
}
#include
using namespace std;
int* add(int x, int y) {
int* sum = new int;
*sum = x + y;
return sum;
}
int* add1(int x, int y) {
int sum = x + y;
return ∑
}
//返回局部静态变量的地址
int* add2(int x, int y) {
static int sum = 0;
cout << "sum ;" << sum << endl;
sum = x + y;
return ∑
}
int main() {
int* sum = nullptr;
cout << *add1(2, 5) << endl;//error 不能使用外部函数局部变量的地址 bad
//接收动态内存分配的地址
sum = add(2, 9);//success 局部的堆空间,必须在外部拿到他的地址,从而对他进行释放
cout <<"sum ;"<
#include
using namespace std;
int main() {
//动态内存被多次释放
int* p = new int[18];
p[0] = 0;
//...
delete[]p;
//...
delete[]p;
//检测释放运行到次处
cout << "come here" << endl;
}
//内存泄露
do {
int* p1 = new int[1024];
} while (1 == 1);
//释放的内存不是申请的地址
int* p2 = new int[10];
p2[0] = 1;
for (int i = 0; i < 10; i++) {
p2++;
cout << *p2 << endl;
}
delete[]p2;//此时p2的地址已经偏移了 4* 10个字节 不再是起初的p2地址,无法释放
cout << "come here p2" << endl;
//释放空指针
int* p3 = NULL;
if (1==0) {//模拟文件是否能打开
p3 = new int;
}
delete p3;
cout << "come here" << endl;
//释放一个内存块,又继续使用
int* p4 = new int;
delete p4;
*p4 = 1;
cout << "come here" << endl;
//越界访问
int* p = new int[10];
memset(p, 0, 10 * sizeof(int));
for (int i = 0; i < 10; i++) {
cout << *(p++) << endl;
}
//下面的都越界
for (int i = 0; i < 10; i++) {
cout << *(p++) << endl;
}