c和指针 动态数组实现

/**
c和指针 第11章 第二题
从标准输入中读取一系列的整数,
把这些值存储在一个动态分配的数组中
并返回这个数组。数组的第一个元素是该数组的长度
其他元素是输入的整数
*/
#include <stdio.h>
#include <stdlib.h>
//定义一个长度,最开始时分配的长度
#define LENGTH 20

int *read_ints()
{
    int *num;
    int tem;
    int count = 0;
    int size = LENGTH;

    //分配内存
    num = malloc((size+1)*sizeof(int));
    //内存分配失败,返回NULL
    if(num==NULL)
    return NULL;

    while(scanf("%d",&tem)!=EOF)
    {
        count++;
        //如果长度大于分配的内存,则需要增加内存,使用realloc分配
        if(count>size)
        {
            size += LENGTH;
            num = realloc(num,(size+1)*sizeof(int));
            if(num==NULL)
            return NULL;
        }
        num[count] = tem;
    }
    if(count<size)
    {
        num = realloc(num,(count+1)*sizeof(int));
        if(num==NULL)
        return NULL;
    }
    num[0] = count;
    return num;
}

int main()
{

    int *array;
    int i;
    array = read_ints();
    for(i = 1;i<=array[0];i++)
    printf("%d ",array[i]);
    return 0;
}

posted on 2012-08-24 10:16  NewPanderKing  阅读(800)  评论(0编辑  收藏  举报

导航