【11-3】编写一个函数,从标准输入读取一个字符串,把字符串复制到动态内存分配的内存中,并返回该字符串的拷贝,这个函数不应该对读入字符串的长度作任何限制!
这个问题比较简单,需要注意字符串输入的结束处理和内存空间的申请的时机。
#include <stdio.h>
#include <string.h>
#include <assert.h>
typedef short int int16_t;
typedef int int32_t;
#define TRUE 1
#define FALSE 0
#define NUL '\0'
#define ARRAY_DEFAULT_SIZE 10
char *read_string() {
int ch;
char *buffer;
int len = 0;
int size = 0;
char *bp = buffer;
do {
ch = getchar();
if(ch == '\n' || ch == EOF) {
ch = NUL;
}
if (len >= size) {
size += ARRAY_DEFAULT_SIZE;
buffer = realloc(buffer, size * sizeof(char));
assert(buffer != NULL);
bp = buffer + len;
}
*bp++ = ch;
len++;
} while (ch != NUL);
bp = malloc(len * sizeof(char));
assert(bp != NULL);
strcpy(bp, buffer);
return bp;
}
int main() {
char *buffer = read_string();
printf("buffer : %s\n", buffer);
if(buffer != NULL) {
free(buffer);
}
return 0;
}