C primer plus自用知识点整理(第十四章)结构和其他数据形式
发布日期:2022-01-20 01:07:21
浏览次数:2
分类:技术文章
本文共 19213 字,大约阅读时间需要 64 分钟。
书籍整理内容:
最近在看C primer plus(加深巩固自己的C语言技巧,为以后学习C++打个基础)。 里面知识针对自己以后要查的点整理出来。 使用工具:visual studio 2013 :https://blog.csdn.net/answerMack/article/details/103766020 :https://blog.csdn.net/answerMack/article/details/103805900 :https://blog.csdn.net/answerMack/article/details/103855794 :https://blog.csdn.net/answerMack/article/details/103870182 https://blog.csdn.net/answerMack/article/details/103891048 https://blog.csdn.net/answerMack/article/details/103953376 https://blog.csdn.net/answerMack/article/details/103978471 :https://blog.csdn.net/answerMack/article/details/104114028 :https://blog.csdn.net/answerMack/article/details/105222269 :https://blog.csdn.net/answerMack/article/details/105338533 第十三章未更新目录
结构体
//* book.c -- one-book inventory */#include#include char * s_gets(char * st, int n);#define MAXTITL 41 /* maximum length of title + 1 */#define MAXAUTL 31 /* maximum length of author's name + 1 */struct book { /* structure template: tag is book */ char title[MAXTITL]; char author[MAXAUTL]; float value;}; /* end of structure template */int main(void){ struct book library; /* declare library as a book variable */ printf("Please enter the book title.\n"); s_gets(library.title, MAXTITL); /* access to the title portion */ printf("Now enter the author.\n"); s_gets(library.author, MAXAUTL); printf("Now enter the value.\n"); scanf_s("%f", &library.value); printf("%s by %s: $%.2f\n", library.title, library.author, library.value); printf("%s: \"%s\" ($%.2f)\n", library.author, library.title, library.value); printf("Done.\n"); return 0;}char * s_gets(char * st, int n){ char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); // look for newline if (find) // if the address is not NULL, *find = '\0'; // place a null character there else while (getchar() != '\n') continue; // dispose of rest of line } return ret_val;}
结构体的初始化:
访问结构成员
结构数组
/* manybook.c -- multiple book inventory */#include#include char * s_gets(char * st, int n);#define MAXTITL 40#define MAXAUTL 40#define MAXBKS 100 /* maximum number of books */struct book { /* set up book template */ char title[MAXTITL]; char author[MAXAUTL]; float value;};int main(void){ struct book library[MAXBKS]; /* array of book structures */ int count = 0; int index; printf("Please enter the book title.\n"); printf("Press [enter] at the start of a line to stop.\n"); while (count < MAXBKS && s_gets(library[count].title, MAXTITL) != NULL && library[count].title[0] != '\0') { printf("Now enter the author.\n"); s_gets(library[count].author, MAXAUTL); printf("Now enter the value.\n"); scanf_s("%f", &library[count++].value); while (getchar() != '\n') continue; /* clear input line */ if (count < MAXBKS) printf("Enter the next title.\n"); } if (count > 0) { printf("Here is the list of your books:\n"); for (index = 0; index < count; index++) printf("%s by %s: $%.2f\n", library[index].title, library[index].author, library[index].value); } else printf("No books? Too bad.\n"); return 0;}char * s_gets(char * st, int n){ char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); // look for newline if (find) // if the address is not NULL, *find = '\0'; // place a null character there else while (getchar() != '\n') continue; // dispose of rest of line } return ret_val;}
程序讨论
嵌套结构
#include#define LEN 20const char * msgs[5] ={ " Thank you for the wonderful evening, ", "You certainly prove that a ", "is a special kind of guy. We must get together", "over a delicious ", " and have a few laughs"};struct names { // first structure char first[LEN]; char last[LEN];};struct guy { // second structure struct names handle; // nested structure char favfood[LEN]; char job[LEN]; float income;};int main(void){ struct guy fellow = { // initialize a variable { "Ewen", "Villard" }, "grilled salmon", "personality coach", 68112.00 }; printf("Dear %s, \n\n", fellow.handle.first); printf("%s%s.\n", msgs[0], fellow.handle.first); printf("%s%s\n", msgs[1], fellow.job); printf("%s\n", msgs[2]); printf("%s%s%s", msgs[3], fellow.favfood, msgs[4]); if (fellow.income > 150000.0) puts("!!"); else if (fellow.income > 75000.0) puts("!"); else puts("."); printf("\n%40s%s\n", " ", "See you soon,"); printf("%40s%s\n", " ", "Shalala"); return 0;}
指向结构的指针
#include#define LEN 20struct names { char first[LEN]; char last[LEN];};struct guy { struct names handle; char favfood[LEN]; char job[LEN]; float income;};int main(void){ struct guy fellow[2] = { { { "Ewen", "Villard" }, "grilled salmon", "personality coach", 68112.00 }, { { "Rodney", "Swillbelly" }, "tripe", "tabloid editor", 432400.00 } }; struct guy * him; /* here is a pointer to a structure */ printf("address #1: %p #2: %p\n", &fellow[0], &fellow[1]); him = &fellow[0]; /* tell the pointer where to point */ printf("pointer #1: %p #2: %p\n", him, him + 1); printf("him->income is $%.2f: (*him).income is $%.2f\n", him->income, (*him).income); him++; /* point to the next structure */ printf("him->favfood is %s: him->handle.last is %s\n", him->favfood, him->handle.last); return 0;}
指针声明
指针访问成员
第一种:- >
第二种:(*him).income 之前写过的程序的例子链接: https://blog.csdn.net/answerMack/article/details/83900027向函数传递结构的信息
函数与结构交互
传递结构成员
#include#define FUNDLEN 50struct funds { char bank[FUNDLEN]; double bankfund; char save[FUNDLEN]; double savefund;};double sum(double, double);int main(void){ struct funds stan = { "Garlic-Melon Bank", 4032.27, "Lucky's Savings and Loan", 8543.94 }; printf("Stan has a total of $%.2f.\n", sum(stan.bankfund, stan.savefund)); return 0;}/* adds two double numbers */double sum(double x, double y){ return(x + y);}
传递结构地址
主函数:
sum(&stan)
求和函数
double sum(const struct funds * money){ return(money->bankfund + money->savefund);}
传递结构
主函数:
sum(stan)
求和函数
double sum(struct funds money){ return(money.bankfund + money.savefund);}
其他结构特性
使用指针:传递地址,且函数为void形式#include使用结构:传递结构#include #define NLEN 30struct namect { char fname[NLEN]; char lname[NLEN]; int letters;};void getinfo(struct namect *);void makeinfo(struct namect *);void showinfo(const struct namect *);char * s_gets(char * st, int n);int main(void){ struct namect person; getinfo(&person); makeinfo(&person); showinfo(&person); return 0;}void getinfo(struct namect * pst){ printf("Please enter your first name.\n"); s_gets(pst->fname, NLEN); printf("Please enter your last name.\n"); s_gets(pst->lname, NLEN);}void makeinfo(struct namect * pst){ pst->letters = strlen(pst->fname) + strlen(pst->lname);}void showinfo(const struct namect * pst){ printf("%s %s, your name contains %d letters.\n", pst->fname, pst->lname, pst->letters);}char * s_gets(char * st, int n){ char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); // look for newline if (find) // if the address is not NULL, *find = '\0'; // place a null character there else while (getchar() != '\n') continue; // dispose of rest of line } return ret_val;}
#include#include #define NLEN 30struct namect { char fname[NLEN]; char lname[NLEN]; int letters;};struct namect getinfo(void);struct namect makeinfo(struct namect);void showinfo(struct namect);char * s_gets(char * st, int n);int main(void){ struct namect person; person = getinfo(); person = makeinfo(person); showinfo(person); return 0;}struct namect getinfo(void){ struct namect temp; printf("Please enter your first name.\n"); s_gets(temp.fname, NLEN); printf("Please enter your last name.\n"); s_gets(temp.lname, NLEN); return temp;}struct namect makeinfo(struct namect info){ info.letters = strlen(info.fname) + strlen(info.lname); return info;}void showinfo(struct namect info){ printf("%s %s, your name contains %d letters.\n", info.fname, info.lname, info.letters);}char * s_gets(char * st, int n){ char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); // look for newline if (find) // if the address is not NULL, *find = '\0'; // place a null character there else while (getchar() != '\n') continue; // dispose of rest of line } return ret_val;}
函数定义中包含返回值,可以返回该结构。
函数声明:struct namect makeinfo(struct namect);结构和结构指针选择
结构中的字符数组和字符指针
结构、指针和malloc()
malloc动态分配内存(详情见12章)与free函数相结合使用
#include#include // for strcpy(), strlen()#include // for malloc(), free()#define SLEN 81struct namect { char * fname; // using pointers char * lname; int letters;};void getinfo(struct namect *); // allocates memoryvoid makeinfo(struct namect *);void showinfo(const struct namect *);void cleanup(struct namect *); // free memory when donechar * s_gets(char * st, int n);int main(void){ struct namect person; getinfo(&person); makeinfo(&person); showinfo(&person); cleanup(&person); return 0;}void getinfo(struct namect * pst){ char temp[SLEN]; printf("Please enter your first name.\n"); s_gets(temp, SLEN); // allocate memory to hold name pst->fname = (char *)malloc(strlen(temp) + 1); // copy name to allocated memory strcpy_s(pst->fname, strlen(temp)+1, temp); printf("Please enter your last name.\n"); s_gets(temp, SLEN); pst->lname = (char *)malloc(strlen(temp) + 1); strcpy_s(pst->lname, strlen(temp)+1,temp);}void makeinfo(struct namect * pst){ pst->letters = strlen(pst->fname) + strlen(pst->lname);}void showinfo(const struct namect * pst){ printf("%s %s, your name contains %d letters.\n", pst->fname, pst->lname, pst->letters);}void cleanup(struct namect * pst){ free(pst->fname); free(pst->lname);}char * s_gets(char * st, int n){ char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); // look for newline if (find) // if the address is not NULL, *find = '\0'; // place a null character there else while (getchar() != '\n') continue; // dispose of rest of line } return ret_val;}
复合字面量和结构(c99)
复合字面量可以不需要变量名!!伸缩型数组成员(c99)
书本例程程序有错误(14.12)
#include#include struct flex{ size_t count; double average; double scores[]; // flexible array member};void showFlex(const struct flex * p);int main(void){ struct flex * pf1, *pf2; int n = 5; int i; int tot = 0; // allocate space for structure plus array pf1 = (struct flex *)malloc(sizeof(struct flex) + n * sizeof(double)); pf1->count = n; for (i = 0; i < n; i++) { pf1->scores[i] = 20.0 - i; tot += pf1->scores[i]; } pf1->average = tot / n; showFlex(pf1); n = 9; tot = 0; pf2 = (struct flex *)malloc(sizeof(struct flex) + n * sizeof(double)); pf2->count = n; for (i = 0; i < n; i++) { pf2->scores[i] = 20.0 - i / 2.0; tot += pf2->scores[i]; } pf2->average = tot / n; showFlex(pf2); free(pf1); free(pf2); return 0;}void showFlex(const struct flex * p){ int i; printf("Scores : "); for (i = 0; i < p->count; i++) printf("%g ", p->scores[i]); printf("\nAverage: %g\n", p->average);}
错误语句:
pf1 = (struct flex *)malloc(sizeof(struct flex) + n * sizeof(double)); pf2 = (struct flex *)malloc(sizeof(struct flex) + n * sizeof(double)); malloc应坚持使用强制类型转换!!!结果:
匿名结构(c11)
使用结构数组的函数
#include#define FUNDLEN 50#define N 2struct funds { char bank[FUNDLEN]; double bankfund; char save[FUNDLEN]; double savefund;};double sum(const struct funds money[], int n);int main(void){ struct funds jones[N] = { { "Garlic-Melon Bank", 4032.27, "Lucky's Savings and Loan", 8543.94 }, { "Honest Jack's Bank", 3620.88, "Party Time Savings", 3802.91 } }; printf("The Joneses have a total of $%.2f.\n", sum(jones, N)); return 0;}double sum(const struct funds money[], int n){ double total; int i; for (i = 0, total = 0; i < n; i++) total += money[i].bankfund + money[i].savefund; return(total);}
把结构内容保存到文件中(待理解+13章内容)
fprintf(见11章)(文件操作见13章,本人未写)
fopen_s(&pbooks,“book.dat”, “a+b”)#include#include #include #define MAXTITL 40#define MAXAUTL 40#define MAXBKS 10 /* maximum number of books */char * s_gets(char * st, int n);struct book { /* set up book template */ char title[MAXTITL]; char author[MAXAUTL]; float value;};int main(void){ struct book library[MAXBKS]; /* array of structures */ int count = 0; int index, filecount; FILE * pbooks; int size = sizeof(struct book); if ((fopen_s(&pbooks,"book.dat", "a+b")) == NULL) { fputs("Can't open book.dat file\n", stderr); exit(1); } rewind(pbooks); /* go to start of file */ while (count < MAXBKS && fread(&library[count], size, 1, pbooks) == 1) { if (count == 0) puts("Current contents of book.dat:"); printf("%s by %s: $%.2f\n", library[count].title, library[count].author, library[count].value); count++; } filecount = count; if (count == MAXBKS) { fputs("The book.dat file is full.", stderr); exit(2); } puts("Please add new book titles."); puts("Press [enter] at the start of a line to stop."); while (count < MAXBKS && s_gets(library[count].title, MAXTITL) != NULL && library[count].title[0] != '\0') { puts("Now enter the author."); s_gets(library[count].author, MAXAUTL); puts("Now enter the value."); scanf_s("%f", &library[count++].value); while (getchar() != '\n') continue; /* clear input line */ if (count < MAXBKS) puts("Enter the next title."); } if (count > 0) { puts("Here is the list of your books:"); for (index = 0; index < count; index++) printf("%s by %s: $%.2f\n", library[index].title, library[index].author, library[index].value); fwrite(&library[filecount], size, count - filecount, pbooks); } else puts("No books? Too bad.\n"); puts("Bye.\n"); fclose(pbooks); return 0;}char * s_gets(char * st, int n){ char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); // look for newline if (find) // if the address is not NULL, *find = '\0'; // place a null character there else while (getchar() != '\n') continue; // dispose of rest of line } return ret_val;}
把//exit(1);注释掉了的下面结果:
链式结构(简介,内容少)
联合简介(union)
用法
匿名联合(c11)
结构和union运算符
枚举类型enum
enum常量为int类型。
用法
#include#include // for strcmp(), strchr()#include // C99 featurechar * s_gets(char * st, int n);enum spectrum { red, orange, yellow, green, blue, violet };const char * colors[] = { "red", "orange", "yellow","green", "blue", "violet" };#define LEN 30int main(void){ char choice[LEN]; int color; bool color_is_found = false; puts("Enter a color (empty line to quit):"); while (s_gets(choice, LEN) != NULL && choice[0] != '\0') { for (color = red; color <= violet; color++) { if (strcmp(choice, colors[color]) == 0) { color_is_found = true; break; } } if (color_is_found) switch (color) { case red: puts("Roses are red."); break; case orange: puts("Poppies are orange."); break; case yellow: puts("Sunflowers are yellow."); break; case green: puts("Grass is green."); break; case blue: puts("Bluebells are blue."); break; case violet: puts("Violets are violet."); break; } else printf("I don't know about the color %s.\n", choice); color_is_found = false; puts("Next color, please (empty line to quit):"); } puts("Goodbye!"); return 0;}char * s_gets(char * st, int n){ char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); // look for newline if (find) // if the address is not NULL, *find = '\0'; // place a null character there else while (getchar() != '\n') continue; // dispose of rest of line } return ret_val;}
把enum spectrum color改为了int color
共享名称空间
typedef简介
typedef和#define
其他复杂声明(指针和数组的解释※※重要)
复杂声明:*、()、[]
函数类复杂声明
typedef建立的声明
函数和指针
// func_ptr.c -- uses function pointers#include#include #include #define LEN 81char * s_gets(char * st, int n);char showmenu(void);void eatline(void); // read through end of linevoid show(void(*fp)(char *), char * str);//函数指针void ToUpper(char *); // convert string to uppercasevoid ToLower(char *); // convert string to uppercasevoid Transpose(char *); // transpose casesvoid Dummy(char *); // leave string unalteredint main(void){ char line[LEN]; char copy[LEN]; char choice; //函数指针 void(*pfun)(char *); // points a function having a // char * argument and no // return value puts("Enter a string (empty line to quit):"); while (s_gets(line, LEN) != NULL && line[0] != '\0') { while ((choice = showmenu()) != 'n') { switch (choice) // switch sets pointer { case 'u': pfun = ToUpper; break; case 'l': pfun = ToLower; break; case 't': pfun = Transpose; break; case 'o': pfun = Dummy; break; } strcpy_s(copy, line);// make copy for show() show(pfun, copy); // use selected function } puts("Enter a string (empty line to quit):"); } puts("Bye!"); return 0;}char showmenu(void){ char ans; puts("Enter menu choice:"); puts("u) uppercase l) lowercase"); puts("t) transposed case o) original case"); puts("n) next string"); ans = getchar(); // get response ans = tolower(ans); // convert to lowercase eatline(); // dispose of rest of line while (strchr("ulton", ans) == NULL) { puts("Please enter a u, l, t, o, or n:"); ans = tolower(getchar()); eatline(); } return ans;}void eatline(void){ while (getchar() != '\n') continue;}void ToUpper(char * str){ while (*str) { *str = toupper(*str); str++; }}void ToLower(char * str){ while (*str) { *str = tolower(*str); str++; }}void Transpose(char * str){ while (*str) { if (islower(*str)) *str = toupper(*str); else if (isupper(*str)) *str = tolower(*str); str++; }}void Dummy(char * str){ // leaves string unchanged}void show(void(*fp)(char *), char * str){ (*fp)(str); // apply chosen function to str puts(str); // display result}char * s_gets(char * st, int n){ char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); // look for newline if (find) // if the address is not NULL, *find = '\0'; // place a null character there else while (getchar() != '\n') continue; // dispose of rest of line } return ret_val;}
总结
关键概念
小结
2020-04-24 大连
(看的有些匆忙,可能太粗糙了,大多粘粘与截图,这个结构自己之前参考别人的写过,所有看这些理论能够懂得更快一些,如果其他人看到,建议自己看看书或者教学视频!!!)加油!!! 13章的文件处理个人可能不更,想学自己翻翻书!!!!! |
转载地址:https://blog.csdn.net/answerMack/article/details/105655872 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
能坚持,总会有不一样的收获!
[***.219.124.196]2024年02月28日 04时10分26秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
c语言中malloc数组,如何在C中对malloc()数组进行一行赋值?
2019-04-21
c语言调存储过程,写留言板–调用存储过程出问题
2019-04-21
c语言编程max,C语言编程题及答案.doc
2019-04-21
android增删改查布局,Android之父_增删改查
2019-04-21
html获取文件路径_HTML 文件路径
2019-04-21
mysql in 有序_mysql中的in排序 mysql按in中顺序来排序
2019-04-21
mysql 行转列 显示_mysql 行转列 (结果集以坐标显示)
2019-04-21
mysql 完全备份恢复吗_MySQL完全备份与恢复
2019-04-21
wpf 绘制矩形_WPF制作倒影效果
2019-04-21
mysql数据库断电恢复_MySQL数据库InnoDB引擎下服务器断电数据恢复方法
2019-04-21
python入门程序异常_Python 入门 之 异常处理
2019-04-21
python 键盘输入int_Python编程 Python如何获取数据
2019-04-21