C语言struct fact_entry *fact_table含义及阶乘代码补全问题
核心概念解释
struct fact_entry *fact_table;这行代码定义了一个指向struct fact_entry结构体类型的指针,后续你可以把它当作动态结构体数组使用:因为输入的n是通过命令行参数传入的,存储阶乘数据的数组长度不固定,所以需要用这个指针接收动态申请的内存空间,之后就可以用fact_table[i]的方式访问数组中第i个结构体元素,和后续的printf访问语法完全匹配。
代码补全步骤
内存分配与阶乘计算
你需要先完成两类操作:申请结构体数组的内存、依次计算每个数的阶乘并填充结构体字段:
- 调用
malloc申请能容纳n+1个struct fact_entry元素的内存(需要存储0到n共n+1个数字的阶乘) - 初始化阶乘初始值:0的阶乘为1
- 循环从1到n依次计算阶乘,同时给每个结构体的三个字段赋值:
n字段存储当前的数字lli_fact存储对应阶乘的长整型数值str_fact需要先申请足够的字符串内存,再把长整型的阶乘值转为字符串存储
内存释放
我们一共申请了两类动态内存:结构体数组本身的内存、每个结构体中str_fact指向的字符串内存,释放顺序要和申请顺序相反:
- 先循环释放每个
fact_table[i].str_fact指向的字符串内存 - 再释放
fact_table本身的内存
补全后的完整代码
#include <stdlib.h> #include <errno.h> #include <stdio.h> #include <string.h> #include <math.h> #define LIMIT 20 struct fact_entry { /* Definition of each table entry */ int n; long long int lli_fact; /* 64-bit integer */ char *str_fact; }; void panic (char *m) { fprintf (stderr, "%s\n", m); exit (0); } int main (int argc, char *argv[]) { int n; int i; struct fact_entry *fact_table; if (argc != 2) panic ("wrong parameters"); n = atoi (argv[1]); if (n < 0) panic ("n too small"); if (n > LIMIT) panic ("n too big"); /* Your code starts here */ // Allocate memory fact_table = (struct fact_entry *)malloc((n + 1) * sizeof(struct fact_entry)); if (fact_table == NULL) { panic("memory allocation failed"); } // Compute fact(n) for i=0 to n long long int current_fact = 1; for (i = 0; i <= n; i++) { fact_table[i].n = i; fact_table[i].lli_fact = current_fact; // 20的阶乘共19位,申请24字节足够存储所有合法范围内的阶乘字符串 fact_table[i].str_fact = (char *)malloc(24 * sizeof(char)); sprintf(fact_table[i].str_fact, "%lld", current_fact); // 更新下一个数的阶乘值 current_fact *= (i + 1); } /* Your code ends here */ // print computed numbers for (i = 0; i <= n; i++) { printf ("%d %lld %s\n", fact_table[i].n, fact_table[i].lli_fact, fact_table[i].str_fact); } /* Your code starts here */ // Free memory for (i = 0; i <= n; i++) { free(fact_table[i].str_fact); } free(fact_table); /* Your code ends here */ return 0; }
内容的提问来源于stack exchange,提问作者Charles De Labra
相关产品推荐
相关产品推荐

