一、C++创建一维数组
type *p = new type [N]
-
type是指具体的数据类型, N代表的是一维数组的列数
每次使用new后都要释放
delete[] p1;
-
二、C++创建二维数组
一般的格式:type (*p)[N] = new type [][N]
type是指具体的数据类型, N代表的是二维数组的列数
另一种格式:不需要写列数
当然在每次使用完动态数组后,需要将其释放
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
char **p2;
int main()
{
FILE *fp1,*fp2,*fp3,*fp4;
if((fp1=fopen("..//1.txt","r"))==NULL)
{
printf("fp1 error occur!\n");
exit(1);
}
if((fp2=fopen("..//2.txt","w"))==NULL)
{
printf("fp2 error occur!\n");
exit(1);
}
if((fp3=fopen("..//gene_length.txt","r"))==NULL)
{
printf("fp3 error occur!\n");
exit(3);
}
if((fp4=fopen("..//q_files.txt","w"))==NULL)
{
printf("fp4 error occur!\n");
exit(3);
}
int i=0,j=0;
char ch;
char ch1[20];
memset(ch1,0,sizeof(ch1));
int flag=0;
int row, col;
fscanf(fp3,"%d",&row);
fscanf(fp3,"%d",&col);
p2 = new char*[row];
for (int i = 0; i < row; i++)
{
p2[i] = new char[col];
memset(p2[i],0,sizeof(p2));
}
while((ch=fgetc(fp1))!=EOF)
{
if(ch!='\n')
{
p2[i][j++]=ch;
}
else
{
p2[i][j]=ch;
for(int z=j+1;z<col;z++)
p2[i][z]='\0';
i++;
j=0;
}
}
for(int p=0; p<=i; p++)
{
if((p2[p][0])=='>'&&(p2[p+1][0])!='>')
{
fprintf(fp2,"%s",p2[p]);
fprintf(fp2,"%s",p2[p+1]);
}
else if((p2[p][0])=='>'&&(p2[p+1][0])=='>')
{
fprintf(fp4,"%s\n",p2[p]);
}
}
for (int i = 0; i < row; i++)
{
delete[] p2[i];
}
delete[] p2;
fclose(fp1);
fclose(fp2);
fclose(fp3);
fclose(fp4);
}
三、创建三维数组
和创建二维数组一样,只需要在添加第三个变量就能完成三维数组的创建。
实例:创建一个动态的高height、行row、列col的三维数组,并随机赋值0-9
#include "iostream"
#include "ctime"
using namespace std;
int main()
{
int hight, row, col;
int i, j,k;
srand((unsigned)time(NULL));
cout << "输入三维数组高,行,列 : ";
cin >> hight >> row >> col;
//动态定义三维数组:
int *** p3;
p3 = new int**[hight];
for (i = 0; i < hight; i++)
p3[i] = new int*[row];
for (i = 0; i < hight; i++)
for (j = 0; j < row; j++)
p3[i][j] = new int[col];
//输入三维数组值:
for (i = 0; i < hight; i++)
for (j = 0; j < row; j++)
for (k = 0; k < col; k++)
p3[i][j][k] = rand() % 10;
//输出三维数组:
cout << "输出三维数组" << endl;
for (i = 0; i < hight; i++)
{
for (j = 0; j < row; j++)
{
for (k = 0; k < col; k++)
cout << p3[i][j][k] << ' ';
cout << endl;
}
cout << endl;
}
//释放三维数组
for (i = 0; i < hight; i++)
for (j = 0; j < row; j++)
delete[]p3[i][j];
for (i = 0; i < hight; i++)
delete[]p3[i];
delete[]p3;
}