动态分配一维数组

    很多时候,在需要用数组来记录一些数据的时候,对于数组的长度我们都是往最大的需求去取,但其实对于很多的输入,数组申请的内存在很多时候浪费了很多。我们可以用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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我要出家当道士

打赏是不可能,这辈子都不可能

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值