注意:
(0) 讲解C语言中的动态数组的申请以及释放(一维/二维/三维);
(1)需要你对C语言中的至少是一维数组非常熟悉, 不流于表面,否则可能稍有难度;
(2)打印使用了C++中的std::cout语法, 主要是方便; (读者不要纠结);
(3)每种申请都配合了一张图解, 便于理解, 应该可以看懂;
(4)注意一点: C语言的中指针变量类型占用4个字节;
1. 动态一维数组的申请与释放
void test0()
{
int array[6] = { 1, 2, 6, 7, 10, 12 };
int* pArray = (int*)malloc(sizeof(int) * sizeof(array) / sizeof(int));
memset(pArray, 0, sizeof(array) / sizeof(int));
for (int i = 0; i < sizeof(array) / sizeof(int); i++) {
pArray[i] = array[i];
}
for (int i = 0; i < sizeof(array) / sizeof(int); i++) {
std::cout << pArray[i] << " ";
}
std::cout << std::endl;
free(pArray);
pArray = NULL;
}
图解:
2. 动态二维数组的申请与释放
void test()
{
int array[3][4] = {
{ 6,2,3,4 },
{ 5,11,15,8 },
{ 8,20,10,11 }
};
int** pArray = (int**)malloc(sizeof(int) * 3);
memset(pArray, 0, sizeof(int) * 3);
for (int i = 0; i < 4; i++) {
pArray[i] = (int*)malloc(sizeof(int) * 4);
memset(pArray[i], 0, sizeof(int) * 4);
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
pArray[i][j] = array[i][j];
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
std::cout << pArray[i][j] << " ";
}
std::cout << std::endl;
}
for (int i = 0; i < 3; i++) {
free(pArray[i]);
pArray[i] = NULL;
}
}
图解:
3. 动态三维数组的申请与释放
void Test()
{
int array[2][3][4] =
{
{
{6,2,3,4},
{5,11,15,8},
{8,20,10,11}
},
{
{0,0,3,4},
{5,0,7,8},
{8,1,18,31}
}
};
int*** pArray = (int***)malloc(sizeof(int) * 2);
memset(pArray, 0, sizeof(int) * 2);
for (int i = 0; i < 2; i++) {
pArray[i] = (int**)malloc(sizeof(int) * 3);
memset(pArray[i], 0, sizeof(int) * 3);
for (int j = 0; j < 3; j++) {
pArray[i][j] = (int*)malloc(sizeof(int) * 4);
memset(pArray[i][j], 0, sizeof(int) * 4);
}
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 4; k++) {
pArray[i][j][k] = array[i][j][k];
}
}
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 4; k++) {
std::cout << pArray[i][j][k] << " ";
}
std::cout << endl;
}
std::cout << std::endl;
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
free(pArray[i][j]);
pArray[i][j] = NULL;
}
free(pArray[i]);
pArray[i] = NULL;
}
}
图解:
课后练习:通过动态申请二维数组, 去存储字符串。
Answer:
void test()
{
char** pArray = (char**)malloc(sizeof(int) * 6);
memset(pArray, 0, sizeof(int) * 6);
for (int i = 0; i < 6; i++) {
pArray[i] = (char*)malloc(50);
memset(pArray[i], 0, sizeof(50));
}
pArray[0] = (char*)"dgsd";
pArray[1] = (char*)"gdgsdhsdg";
pArray[2] = (char*)"dg";
pArray[3] = (char*)"hf";
pArray[4] = (char*)"h";
pArray[5] = (char*)"d";
std::cout << pArray[0] << std::endl;
std::cout << pArray[1] << std::endl;
std::cout << pArray[2] << std::endl;
std::cout << pArray[3] << std::endl;
std::cout << pArray[4] << std::endl;
std::cout << pArray[5] << std::endl;
}
|