/*
* 编写一个函数,从标准输入读取一个字符串,把字符串复制到动态分配的内存中,并返回
* 该字符串的拷贝。这个函数不应该对输入的字符串的长度作任何限制
*/
/*
* Read a string and return a copy of it in dynamiccally allocated memory.
* There is no limit (other than the amount of dynamic memory availale) on the size of the string.
*/
/*
* The strategy used in this solution is to keep a dynamically allocated bufferin the readsting
* function. If this fills while reading a string, it is enlarged. The increment, DELTA, can be
* turned to achieve a balance between minimizing wasted space and minimizing the number of real-
* locations that occur. The assert macro is used to abort the problem if any memory allocation
* fails. A new chunk of memory is allocated for the copy of the string that is returned to the
* caller-this avoids the overhead of dynamically growing the array from scratch each time ia
* string is read.
*/
#include <stdlib.h> #include <stdio.h> #include <assert.h>
#define DELTA 256
char *readstring() { static char *buffer = NULL; static int buffer_size = 0; int ch; int len; char *bp;
bp = buffer; len = 0; /*-----------------------------------?----------------------------------------*/ /* Get characters one at a time until a newline is read or EOF is reached */ do{ ch = get(); if( ch == '\n' || ch == EOF ) ch == '\0';
/* if the buffer is full,make it bigger */ if( len >= buffer_size ) { buffer_size += DELTA; buffer = realloc( buffer, buffer_size ); assert( buffer != NULL ); bp = buffer + len; }
*bp++ = ch; len += 1; } while( ch != '\0' ); /*------------------------------------?---------------------------------------*/ /* make a copy of the string to ruturn */ bp = malloc( len ); assert( bp != 0 ); strcpy( bp, buffer ); return bp; }
|
阅读(1329) | 评论(0) | 转发(0) |