55 lines
1.4 KiB
C
55 lines
1.4 KiB
C
// 编写一个程序,要求用户输入一串字符,然后动态创建一个字符数组,并将用户输入的字符存储到数组中。然后,使用realloc函数将数组的大小扩展为原来的两倍,并继续接受用户输入的字符,直到用户输入字符为换行符( '\n')。最后,打印数组中存储的所有字符。
|
||
#include <stdio.h>
|
||
#include <stdlib.h>
|
||
#include <string.h>
|
||
|
||
char *
|
||
str_cpy(char *dest, const char *src)
|
||
{
|
||
int cnt;
|
||
while (src[cnt++])
|
||
;
|
||
|
||
char *res = (char *)malloc(cnt * sizeof(char *));
|
||
if (NULL == res)
|
||
{
|
||
perror("malloc");
|
||
exit(0);
|
||
}
|
||
|
||
for (int i = 0; i < cnt; i++)
|
||
res[i] = src[i];
|
||
|
||
return res;
|
||
}
|
||
|
||
int main()
|
||
{
|
||
char s1[100]; // 相当于 char *s1 = (char *)malloc(100 * sizeof(char *));
|
||
printf("请输入一个字符串: ");
|
||
// scanf("%s", s1);
|
||
fgets(s1, sizeof(s1), stdin); // scanf() 不能接收换行,故改用 fgets()
|
||
char *s2 = str_cpy(s2, s1);
|
||
|
||
int tmp_size = strlen(s2);
|
||
|
||
// 扩展数组大小
|
||
s2 = (char *)realloc(s2, 2 * tmp_size);
|
||
if (NULL == s2)
|
||
{
|
||
perror("realloc");
|
||
exit(0);
|
||
}
|
||
printf("请继续输入字符, 输入换行符结束输入\n");
|
||
char *ch;
|
||
s2[tmp_size - 1] = ' ';
|
||
while ((ch = getchar()) != '\n')
|
||
{
|
||
s2[tmp_size++] = ch;
|
||
}
|
||
|
||
printf("结果为: %s\n", s2);
|
||
free(s2);
|
||
|
||
return 0;
|
||
} |