35 lines
874 B
C
35 lines
874 B
C
|
// 编写一个程序,要求用户输入一个字符串,然后动态创建一个字符数组,使其能够容纳用户输入的字符串。然后将用户输入的字符串复制到动态创建的数组中,并打印该字符串。
|
||
|
#include <stdio.h>
|
||
|
#include <stdlib.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];
|
||
|
printf("请输入一个字符串: ");
|
||
|
// scanf("%s", s1);
|
||
|
fgets(s1, sizeof(s1), stdin); // scanf() 不能接收换行,故改用 fgets()
|
||
|
char *s2 = str_cpy(s2, s1);
|
||
|
printf("s2 被复制后的结果为: %s", s2);
|
||
|
free(s2);
|
||
|
|
||
|
return 0;
|
||
|
}
|