题目:
编写一个符合以下描述的函数,首先,
询问用户需要输入多少个单词,然后,接受用户输入的单词,并显示出来。使用malloc(),创建一个动态数组,该数组内含相应的指向chat的指针(注意,由于数组的每个元素都是执行char的指针,所以用于存储malloc()返回值的指针应该是一个指向指针的指针,且它所指向的指针指向char)。
在读取字符串时,该程序应该把单词读入一个临时的chat数组,使用malloc()分配足够的存储空间来存储单词,并把地址存入该指针数组(该数组中每个元素都是指向char的指针)。
然后,从临时数组中把单词拷贝到动态分配的存储空间中。
源代码:
这里分了三个源文件编写(你可以合并到一个源文件当中)
word-sta.h:
#include <stdio.h>
#include <stdlib.h>
void words_allo(char ** ptd,int i);
void words_show(char ** ptd,int i);
word-sta.c:
#include "word-sta.h"
#include <string.h>
void words_allo(char ** ptd,int i){
int num;
char ch[40];
char * ch_point;
for(int x = 0; x < i;x++){
printf("请输入单词: ");
scanf("%s",ch);
num = strlen(ch)+1;
char * ch_point = (char *)malloc(num * sizeof(char));
strcpy(ch_point,ch);
*(ptd+x) = ch_point;
}
}
void words_show(char ** ptd,int i){
printf("输入的单词时: ");
for(int x = 0;x < i;x++){
printf("%s ",*(ptd+x));
}
printf("\n结束");
free(ptd);
}
word-main.c:
#include "word-sta.h"
int main(){
int i;
printf("请输入你需要输入的单词数量: ");
scanf("%d",&i);
char ** ptd = (char **) malloc(i * sizeof(char *));
words_allo(ptd,i);
words_show(ptd,i);
return 0;
}
演示效果:
如果朋友你感觉文章的内容对你有帮助,可以点赞,关注文章和专栏以及关注我哈,嘿嘿嘿我会定期更新文章的,谢谢朋友你的支持哈