输入字符串的动态分配
Dynamic allocation of input string
我编写了以下函数来在键入时动态分配输入字符串,而不询问用户它有多少个字符。
#include<stdio.h>
#include<stdlib.h>
char* dyninp (char str[], int *n) {
char ch;
int i = 0;
do {
ch = getchar();
str = (char *) realloc(str, (i+1)*sizeof(char));
str[i] = ch;
i++;
} while (ch != '\n');
/*substitute '\n' with '[=10=]'*/
str[i-1] = '[=10=]';
if (n != NULL) {
/*i contains the total lenght, including '[=10=]'*/
*n = i-1;
}
/*because realloc changes array's address*/
return str;
}
/*it is called in this way:
char *a;
int n;
a = dyninp (a, &n);
*/
此代码有效,但我对此有一些疑问:
为什么有效?
不明白为什么,我执行的时候,还可以在回车前删除字符。 getchar()
函数每次迭代只读取一个字符,写入数组,所以我怎么能删除一些呢?
如果 getchar()
在接收到 '\127' 时删除了前一个字符,那么循环应该像处理任何其他字符一样继续执行。但这不会发生,因为,当循环结束时,"i" 总是包含确切数量的元素。
我的代码高效吗?如果不是,我怎样才能让它变得更好(甚至使用内置函数)?
我编写了以下函数来在键入时动态分配输入字符串,而不询问用户它有多少个字符。
#include<stdio.h>
#include<stdlib.h>
char* dyninp (char str[], int *n) {
char ch;
int i = 0;
do {
ch = getchar();
str = (char *) realloc(str, (i+1)*sizeof(char));
str[i] = ch;
i++;
} while (ch != '\n');
/*substitute '\n' with '[=10=]'*/
str[i-1] = '[=10=]';
if (n != NULL) {
/*i contains the total lenght, including '[=10=]'*/
*n = i-1;
}
/*because realloc changes array's address*/
return str;
}
/*it is called in this way:
char *a;
int n;
a = dyninp (a, &n);
*/
此代码有效,但我对此有一些疑问:
为什么有效?
不明白为什么,我执行的时候,还可以在回车前删除字符。getchar()
函数每次迭代只读取一个字符,写入数组,所以我怎么能删除一些呢?
如果getchar()
在接收到 '\127' 时删除了前一个字符,那么循环应该像处理任何其他字符一样继续执行。但这不会发生,因为,当循环结束时,"i" 总是包含确切数量的元素。我的代码高效吗?如果不是,我怎样才能让它变得更好(甚至使用内置函数)?