C语言中一些数组和指针的含义:
char ptr[100]="hello world";
ptr:一维数组首元素的地址 ptr+1 …1
&ptr:一维数组的地址 &ptr +1…100
*(&ptr)=ptr:对一维数组的地址取值等于一维数组首元素的地址
char ktr[3][100]={"hello1","hello2","hello3"};
ktr:二维数组的首个一维数组的地址;
&ktr:二维数组的地址
*ktr:二维数组的首个一维数组的首元素的地址
**ktr:二维数组的首个一维数组的首元素的值
*(&ktr)=ktr:对二维数组取值等于首个一维数组的地址
char str[2][2][100]={{"hello4","hello5"},{"hello6","hello7"}};
str:三维数组中首个二维数组的地址;
&str:三维数组的地址;
*str:三维数组中首个二维数组的首个一维数组的地址;
**str:三维数组中首个二维数组的首个一维数组的首个元素的地址;
***str:三维数组中首个二维数组的首个一维数组的首个元素的值;
//指针数组实际上还是一个一维数组,只不过里面保存的是指针;
char *wtr[3]={"hello8","hello9","hello10"};
wtr:首个元素的地址
#include<iostream>
using namespace std;
void print1(char* ptr)
{
}
void print2(char(*str)[100])
{
}
void print3(char(*ktr)[2][100])
{
}
void print4(char** wtr)
{
}
int main()
{
char ptr[100] = "hello world";
char ktr[3][100] = { "hello1","hello2","hello3" };
char str[2][2][100] = { {"hello4","hello5"},{"hello6","hello7"} };
char* wtr[3] = { "hello8","hello9","hello10" };
print1(ptr);
print2(ktr);
print3(str);
print4(wtr);
return 0;
}
C语言中动态分配内存:malloc 和 free
#include<stdio.h>
#include<stdlib.h>
int main()
{
//void *malloc(size_t size);
//void free(void *addr);
char *ptr = (char *)malloc(sizeof(char) * 100);//指针赋值一定是相同类型;
int *p_arr = (int *)malloc(sizeof(int) *100);//400
if (ptr == NULL)
{
perror("malloc error!");
exit(1);
}
memset(ptr, 0, sizeof(char) * 100);
strcpy(ptr, "hello world!");
free(ptr);//free函数如何知道要释放多少内存空间?
//malloc free--->new delete
ptr = NULL;
return 0;
}
c++中新增 new 和 delete
#include<iostream>
using namespace std;
int main()
{
//new delete使用代码
char *p = new char('a');
cout << *p << endl;
char *ptr = new char[100];
delete p;
delete[] ptr;
//分配二维数组
int(*p)[5] = new int[4][5];//整齐的二维数组
char(*ptr)[100] = new char[3][100];
/*int **array2;
array2 = new int *[2];
for (int i = 0; i < 2; i++)
{
array2[i] = new int[3];
}
array2 = new int* [2];
array[0] = new int[10];
array[1] = new int[20];
*/ //不提倡这种写法,更适合分配不规则的多维数组:地图
//分配三维数组
//int* p_arr = new int[10]{1,2,3,4,5};
//initializer_list
//for (int i; i < 10; i++)
//{
// cout << p_arr[i] << endl;
//}
return 0;
}
new delete VS malloc free
1、new delete :(暂时)运算符 malloc free : 函数
2、new delete : 按照类型的个数为单位 malloc free : 按照字节为单位分配
3、new delete : 可以初始化 malloc free : 只能手动初始化
(关于初始化:最好手动初始化!默认初始化都是0)
4、new delete : 如果分配失败会产生异常; malloc free :返回NULL
5、new 底层调用的是malloc delete 底层调用的是free
6、new malloc : 频繁分配小内存会导致出现内存碎片,同时会增加开销;池化技术:内存池!!
7、关于多维数组的分配:规则的多维数组(int(*p)[3] = new int[3][3]、不规则的多维数组(int * *array);
8、C语言中 NULL : #define NULL(void*)0
c++增加 nullptr;
char* ptr = nullptr;