- 题目大纲
- 解法一
- 解法二
编写一个符合一下描述的函数。首先,询问用户需要输入多少个单词。然后,接受用户输入的单词,并显示出来。使用malloc()并回答第一个问题(即要输入多少个单词),创建一个动态数组,该数组包含指向char的指针(注意,因为数组的每个元素都是指向char的指针,所以用于存储malloc()返回值的指针应该是一个指向指针的指针,且它所指向的指针指向char)。在读取字符串时,该程序应该把单词读入一个临时的char数组,使用malloc()分配足够的内存空间来存储单词,并把地址存入该指针数组(该数组中的每个元素都是指向char的指针)。然后,从临时数组中吧单词复制到动态分配的存储空间中。因此,有一个字符指针数值,每个指针都指向一个对象,该对象的大小正好能容纳要存储的特定单词。下面是该程序的一个运行示例:
How many words do you wish to enter? 5 Enter 5 words now: I enjoyed doing this exercise Here are your words: I enjoyed doing exercise解法一
代码如下;
#include#include #include int main() { int amount; printf("How many words do you wish to enter?"); scanf("%d",&amount); printf("Enter %d words now: ",amount); char **pst = (char ** )malloc(amount * sizeof(char *)); for(int i = 0;i < amount; i++) { char temp[100]; scanf("%s",temp); int length = strlen(temp); char* str = (char*)malloc(length * sizeof(char)); //获取用户输入的字符串长度,并创建一个长度匹配的字符串 strcpy(str,temp); *(pst + i) = str; //将字符串指针指向新创建的字符串 } for(int i = 0; i < amount; i++ ) { printf("%sn",*(pst + i)); } free(pst); printf("nAll Done!n"); return 0; }
本解法运用灵活运用指针,不足的是temp数组的长度是定值,容易出现bug(当然,应该没人用超过100个字母的单词吧~)
解法二代码如下:
#include#include void copy(char *p1,char *p2,int n); int main() { int words_num;//用户准备输入单词的数量 char ch; printf("How many words do you wish to enter?") ; scanf("%d", &words_num); getchar(); char * p[words_num];// 定义指针数组 printf("Enter %d words now:",words_num); for(int i = 0;i


