版权声明:此文为博主原创文章,转载请注明出处 https://blog.csdn.net/Alex_mercer_boy/article/details/81982383
《C Primer Plus》第6版 编程练习 第十二章 第九题
呃,题目太长了,就不发了.
恳请各位大佬用 PC 端查看,美感,inportant!!!
目录 (如果无法使用,可以选用右侧的目录选项)
源码:
#include <stdio.h>
#include <stdlib.h> //提供 system() 的原型
#include <string.h> //提供字符串处理函数
#define LEN 30 //用户输入单词的长度
void Get_words(void);
int main(void)
{
int ch;
Get_words();
while (ch = getchar()) //防止突然退出
{
continue;
}
return 0;
}
void Get_words(void)
{
int wordsnum = 0; //单词数量
int ct = 0; //count 缩写
char ** pwords;
char temp[LEN];
printf("How many words do you wish to enter? ");
while (scanf_s("%d", &wordsnum) != 1)
{
puts("That's not a value number, try again: ");
continue; //获取合法输入
}
/* 动态分配内存 */
pwords = (char **)malloc(wordsnum * sizeof(char *));
printf("Enter %d words now: \n", wordsnum);
for (ct = 0; ct < wordsnum; ct++)
{
while (scanf_s("%s", temp, LEN) != 1)
{
printf("%s is not a value word, try again:\n", temp);
continue; //获取合法单词
}
int len = strlen(temp); //获取单词长度(还有一个储存空字符)
/* 动态分配内存 +1 储存空字符*/
pwords[ct] = (char *)malloc(len * sizeof(char) + 1);
//拷贝字符串
strcpy_s(pwords[ct],len + 1, temp);
}
puts("Here are your words:"); //打印结果
for (ct = 0; ct < wordsnum; ct++)
{
puts(pwords[ct]);
free(pwords[ct]); //打印完后就释放内存
}
free(pwords); //因为分配了2次,所以需要释放两次
}
分析:
- 二维数组,稀疏数组动态内存分配
也就是一个不规则的矩形
这里使用分次分别分配内存的方法,即先根据用户输入“需要输入的单词数”
进行一次分配,再根据字符串长度对数组的数组分配。那么,好处是什么呢?
可以不浪费一点内存,尽其所用!(当然,现在没什么用)
或许有读者会注意到,我在第二次分配时,sizeof(len) + 1
这是因为定义的是指针的指针,为字符串分配内存需要再 + 1 (储存空字符)
得出这一些列方法,还是少不了 度娘的帮助,也推荐大家以后这样做。
- 字符串拷贝函数 strcpy_s() 函数
我不得不吐槽 VS2017 了,天天报错,unsafe ,
下面是函数原型
_ACRTIMP errno_t __cdecl strcpy_s(
_Out_writes_z_(_SizeInBytes) char* _Destination,
_In_ rsize_t _SizeInBytes,
_In_z_ char const* _Source
);
参数分别是:
- 目标字符串
- 待拷贝字符串的长度/大小, 大小用 sizeof() 函数,
- 源字符串
这里还有一个释放内存:(分两次释放)
因为分配了两次(单词数 + 字符串长度),所以也需要释放两次
运行测试:
Alex Mercer (boy) 鸣谢!