C语言-用动态分配内存方法处理多个字符串的输入
2020-01-11 本文已影响0人
广陵周惊蛰
问题描述:用动态分配内存方法处理多个字符串的输入
源代码:
/*用动态分配内存方法处理多个字符串的输入*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
int i,n;
char *color[20],str[15];
printf("Please input some words about color:\n");
scanf("%s",str);
while(str[0]!='#'){
color[n]=(char *)malloc(sizeof(char)*(strlen(str)+1));/*动态分配*/
strcpy(color[n],str);/*将输入的字符串赋值给动态内存单元*/
n++;
scanf("%s",str);
}
printf("These words are:");
for(i=n-1;i>=1;i--){/*反序输出*/
printf("%s ",color[i]);
free(color[i]);
}
return 0;
}
运行结果:
用动态分配内存方法处理多个字符串的输入程序参数:
- 输出大小: 154.72265625 KiB
- 编译时间: 0.31s