?C中动态内存的分配通过malloc创建
int* p=(int*)malloc(sizeof(int));
?创建了一个大小为int的内存段
创建多字节内存段
int*p=(int*)malloc(sizeof(int)*3);
?创建4行3列动态二维数组
使用二级指针指向一维数组(里面存储是一级指针),每个一级指针指向一段内存段。
打印验证
#include<stdio.h>
#include<stdlib.h>
int main()
{
int** p = (int**)malloc(sizeof(int*)*4);
for (size_t i = 0; i < 4; i++)
{
p[i] = (int*)malloc(sizeof(int)*3);
}
//赋值 并打印
for (size_t i = 0; i < 4; i++)
{
for (size_t j = 0; j < 3; j++)
{
p[i][j] = i * j;
printf("%d\t", p[i][j]);
}
printf("\n");
}
printf("\n");
return 0;
}
C++动态内存申请
#include<iostream>
using namespace std;
int main()
{
int** pp = new int* [4];
for (size_t i = 0; i < row; i++)
{
pp[i] = new int[3];
}
//初始化数据
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
pp[i][j] = i * j;
printf("%d\t", pp[i][j]);
}
printf("\n");
}
return 0;
}
?以下代码通过传参方式修改数据
C形参是三级指针方式,C++形参采用引用方式
#include<iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int** createArray2D(int row, int cols)
{
//int *pArray=(int*)malloc(sizeof(int)*3)
int** pArray = (int**)malloc(sizeof(int*) * row);
if (pArray == NULL)
return NULL;
for (int i = 0; i < row; i++)
{
//一级指针
pArray[i] = (int*)malloc(sizeof(int) * cols);
}
return pArray;
}
//传参修改二维数组动态分配
void mallocArray2D(int*** pArray, int row, int col)
{
for (size_t i = 0; i < row; i++)
{
for (size_t j = 0; j < col; j++)
{
(*pArray)[i][j] = i + 2 * j;
}
printf("\n");
}
}
//C++创建二维动态数组
int** createArray2DByNew(int row, int col)
{
int** pp = new int* [row];
if (pp == nullptr)
return nullptr;
for (size_t i = 0; i < row; i++)
{
pp[i] = new int[col];
}
return pp;
}
//引用方式修改
void modifyArray2D(int**& pArray,int row,int col)
{
for (size_t i = 0; i < row; i++)
{
for (size_t j = 0; j < col; j++)
{
pArray[i][j] = i * j + 2;
}
}
}
int main()
{
//c申请
#if 0
int** p = createArray2D(4, 3);
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
p[i][j] = i * j;
printf("%d\t", p[i][j]);
}
printf("\n");
}
mallocArray2D(&p, 4, 3);
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
printf("%d\t", p[i][j]);
}
printf("\n");
}
#endif
#if 1
//C++申请
int* p = new int[3];
//int** pp = new int* [5];
int **pp=createArray2DByNew(4,3);
//初始化数据
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
pp[i][j] = i * j;
printf("%d\t", pp[i][j]);
}
printf("\n");
}
//修改数据
modifyArray2D(pp,4,3);
//输出
cout << endl;
for (size_t i = 0; i < 4; i++)
{
for (size_t j = 0; j < 3; j++)
{
cout << pp[i][j] <<"\t";
}
cout << endl;
}
#endif
return 0;
}
|