按输入整型数量分配内存

来源:互联网 发布:nginx 过滤ip 编辑:程序博客网 时间:2024/06/10 02:42

输入任意多的整数,以EOF结束;

目的:使数组分配到的内存刚好为输入整数的总数量+1;其中第一个元素为输入整数的总数量,其后的元素为输入的整数;

输入:

1 3 5 4 6 7

输出:

6 1 3 5 4 6 7


有一些关于堆和栈的基础知识:


函数体内声明数组最大为2M左右,而用动态分配则没有这个限制!!!


堆(Heap)栈(Stack)

一、预备知识—程序的内存分配 
一个由c/C++编译的程序占用的内存分为以下几个部分 
1、栈区(stack)— 由编译器自动分配释放 ,存放函数的参数值,局部变量的值等。其操作方式类似于数据结构中的栈。 
2、堆区(heap) — 一般由程序员分配释放, 若程序员不释放,程序结束时可能由OS回收 。注意它与数据结构中的堆是两回事,分配方式倒是类似于链表,呵呵。 
3、全局区(静态区)(static)—,全局变量和静态变量的存储是放在一块的,初始化的全局变量和静态变量在一块区域, 未初始化的全局变量和未初始化的静态变量在相邻的另一块区域。 - 程序结束后有系统释放 
4、文字常量区 —常量字符串就是放在这里的。 程序结束后由系统释放 
5、程序代码区—存放函数体的二进制代码。 

例子程序 
//main.cpp 
int a = 0; 全局初始化区 
char *p1; 全局未初始化区 
main() 
int b; 栈 
char s[] = "abc"; 栈 
char *p2; 栈 
char *p3 = "123456"; 123456\0在常量区,p3在栈上。 
static int c =0; 全局(静态)初始化区 
p1 = (char *)malloc(10); 
p2 = (char *)malloc(20); 
分配得来得10和20字节的区域就在堆区。 
strcpy(p1, "123456"); 123456\0放在常量区,编译器可能会将它与p3所指向的"123456"优化成一个地方。 

附上代码:

#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个intp = (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;}






1 0