在使用数组时,需要事先确定数组的大小。
因为要求int array[n]括号里的n必须为常量,于是天真的认为在定义n的时候写上一个const int n就可以解决问题了,经过尝试失败。
上网一搜,有很多方法,比如使用结构,使用链表等。
下面给出一种简单的方法,使用malloc函数。
<span style="font-size:18px;">int n;
double* shuzu = (double*)malloc(n*sizeof(double));//定义动态数组 相当于 double shuzu[n]</span>
为了说明给出的方法和普通的数组是一样的,给出示例程序。
#include<iostream>
#include<malloc.h>
using namespace std;
int main()
{
double* a = (double*)malloc(3*sizeof(double));
a[0] = 5.22;
a[1] = 2.11;
a[2] = 1.55;
for(int i=0; i<3; i++)
cout<<a[i]<<", ";
cout<<endl;
system("pause");
return 1;
}
程序的结果如下图:
欢迎讨论changwn@mail.nankai.edu.cn