很多时候,在需要用数组来记录一些数据的时候,对于数组的长度我们都是往最大的需求去取,但其实对于很多的输入,数组申请的内存在很多时候浪费了很多。我们可以用malloc来动态的为数组分配内存。例如下例,输入一个数字(小于1000000),输出数字范围之内的一个数,这个数必须是两个数的平方和(包含0);
#include <stdio.h>
#include <malloc.h>
#include <math.h>
typedef struct{
int sum;
int first;
int second;
} *array,num;
#define LENGTH (array)malloc(sizeof(num)*number)
int main(void)
{
array head;
int i=0,j=0,count=0,tmp;
double num;
scanf("%lf",&number);
tmp = (int)sqrt(number);
head = LENGTH;
if(head!=NULL)
{
for(i=0;i<=tmp;i++)
for(j=i+1;j<=tmp;j++)
{
int sum = i*i+j*j;
if(sum<=(int) number)
{
head[count].first=i;
head[count].second=j;
head[count].sum = sum;
count++;
}
}
}
for(i=0;i<count;i++)
printf("%d + %d = %d\n",head[i].first,head[i].second,head[i].sum);
free(head);
return 0;
}