1、定義一個指針類型
如:typedef double* DoubleArrayPtr;
2、聲明一個指針變量
如: DoubleArrayPtr a;
3、調用new
a = new double[ array_size ];
4:、動態數組的長度在方括號中給出
5、像普通數組那樣使用
6、調用delete [ ]
如:delete [ ] a;
[cpp]
// String.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<cstdlib>
#include<cstddef>///******
typedef int* IntArrayPtr; ///(1)
void fill_array(int a[] , int size);
void sort(int a[] , int size);
int main(int argc, char* argv[])
{
using namespace std;
cout<<"This program sorts numbers from highest to lowest .\n";
int array_size;
cout<<"How many numbers will be sorted?\n";
cin>>array_size;
IntArrayPtr a;///(2)
///創建動態數組
a = new int[array_size]; ///(3)
fill_array(a, array_size);
sort(a, array_size);
cout<<"In sorted order the numbers are :\n";
for(int index = 0; index < array_size ; index++)
{
cout<<a[index]<<" ";
}
cout<<endl;
delete [] a; //(5)
return 0;
}
void fill_array(int a[] ,int size)
{
using namespace std;
cout<<"Enter "<<size<<" integers.\n";
for (int index = 0; index < size ;index++)
cin>>a[index];
}
void sort(int a[] , int size)
{
int i , j ;
//選擇排序
///將數組降序排序
for(i = 0; i < size - 1 ; i++)
for( j = i +1; j < size ; j++)
{
if( a[i] < a[j] )
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}