《C和指针》练习题11.11

 

问题

编写一个函数,从标准输入读取一列整数,把这些值存储于一个动态分配的数组中并返回这个数组。函数通过观察EOF判断输入列表是否结束。数组的第一个数是数组包含的值的个数,他的后面就是这些整数值

 

代码

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

#define N 50

int *readline(void);

void main(void)
{
	int *string = readline();
	printf("%d\n",*string);
	free(string);
	
}

/* 为一列整数动态分配空间
 * 输入:一列整数值
 * 处理:动态分配合适大小的堆空间,并将这一列数存入
 * 返回:指向堆空间的指针
 */
int *readline()
{
	int *array = NULL;
	int size;

	size = N;	//堆空间的初始大小
	array = (int *)malloc( (size+1)*sizeof(int) ); //array[1] - array[size]用于存储数值
	if( NULL == array )
	{//分配空间失败
		printf("malloc faild\n");
		exit(-1);
	}

	int value;
	int count = 0;	
	printf("\n>>");
	while( scanf("%d",&value) == 1 )
	{
		count++;
		if( count > size )
		{//动态增加内存块的空间,N个单元
			size += N;
			array = realloc( array, (size+1)*sizeof(int) );
			if( NULL == array )
			{//修改空间失败
				printf("realloc faild\n");
				exit(-1);
			}
		}
		if( count < size )
		{//动态减小内存块的空间,精确调整空间大小
			array = realloc( array, (count+1)*sizeof(int) );
			if( NULL == array )
			{//修改空间失败
				printf("realloc faild\n");
				exit(-1);
			}
		}
		array[count] = value;	//填充数值
		printf("\n>>");
	}
	array[0] = count;
	return array;
}	

 

结果