输入任意多的整数,以EOF结束;
目的:使数组分配到的内存刚好为输入整数的总数量+1;其中第一个元素为输入整数的总数量,其后的元素为输入的整数;
如
输入:
1 3 5 4 6 7
输出:
6 1 3 5 4 6 7
有一些关于堆和栈的基础知识:
函数体内声明数组最大为2M左右,而用动态分配则没有这个限制!!!
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<algorithm>
#include<cstring>
#include<string>
#include<iostream>
#define ms(x,y) memset(x,y,sizeof(x))
const int MAXN=100;
const int INF=1<<30;
using namespace std;
int *input()
{
int *p = (int *)malloc(MAXN * sizeof(int));//先分配MAXN个int
if(p == NULL) return NULL;
int count = 1;
while(scanf("%d", p+count)==1){
count++;
if(count >= MAXN){//输入的数量>=MAXN,在原内存块尾部增加1个int
p = (int *)realloc(p, (count+1) * sizeof(int));
if(p == NULL) return NULL;
}
}
if(count < MAXN)//输入数量<MAXN,在原内存块尾部删除多余的内存
p = (int *)realloc(p, count * sizeof(int));
p[0] = count-1;
return p;
}
int main()
{
//freopen("in.txt","r",stdin);
int *p = input();
if(p == NULL){
printf("malloc failure\n");
exit(1);
}
printf("%d", p[0]);
for(int i=0; i<p[0]; i++){
printf("% d", p[i+1]);
}
printf("\n");
return 0;
}
原文:http://blog.csdn.net/u013351484/article/details/41848573