您好,欢迎访问一九零五行业门户网

C程序示例,演示可变长度数组的用法

假设我们负责建立一个图书馆系统,用于监控和查询图书馆的各种操作。现在我们被要求实现三个不同的命令,分别执行以下操作:
使用命令1,我们可以记录在书架x上插入一本有y页的书。
使用命令2,我们可以打印出书架x上第y本书的页码。
使用命令3,我们可以打印出书架x上的书的数量。
这些命令以2d数组的形式给出,格式为{命令类型,x,y}。如果没有y值,则默认值为0。我们打印给定命令的结果。
因此,如果输入如下:书架数量=4,查询数量=4,输入数组= {{1,3,23},{1,4,128},{2,3,0},{3,4,0}};那么输出将是
231
command 1 inserts a book with 23 pages on shelf 3.command 2 inserts a book with 128 pages on shelf 4.command 3 prints the page number of book 0 on shelf 3.command 4 prints the number of books on shelf 3.
为了解决这个问题,我们将按照以下步骤进行:
b := 大小为s的新数组p := 大小为s的新数组初始化 i := 0,当 i < s 时,更新(增加 i 1),执行以下操作:b[i] := 0p[i] := 新数组初始化 loopcount := 0,当 loopcount < q 时,更新(增加 loopcount 1),执行以下操作 −qtype := q_array[loopcount, 0]如果 qtype 与 1 相同,则 −x := q_array[loopcount, 1]y := q_array[loopcount, 2]b[x] := b[x] + 1p[x] := 释放 p[x] 指向的对象并返回大小为b[x]p[x, b[x] - 1] = y否则,当 qtype 与 2 相同,则 −x := q_array[loopcount, 1]y := q_array[loopcount, 2]打印 p[x, y]否则x := q_array[loopcount, 1]打印 b[x]如果 b 不为空,则 −释放 b 获取的内存初始化 i := 0,当 i < s 时,更新(增加 i 1),执行以下操作 −如果 p[i] 不为空,则 −释放 p[i] 获取的内存如果 p 不为空,则 −释放 p 获取的内存示例让我们看一下以下实现以更好地理解 −
#include <stdio.h>#include <stdlib.h>void solve(int s, int q, int q_array[][3]){ int* b; int** p; b = (int*)malloc(sizeof(int)*s); p = (int**)malloc(sizeof(int*)*s); for(int i = 0; i < s; i++) { b[i] = 0; p[i] = (int*)malloc(sizeof(int)); } int loopcount; for(loopcount = 0; loopcount < q; loopcount++) { int qtype; qtype = q_array[loopcount][0]; if (qtype == 1) { int x, y; x = q_array[loopcount][1]; y = q_array[loopcount][2]; b[x] += 1; p[x] = realloc(p[x], b[x]*sizeof(int)); p[x][b[x] - 1] = y; } else if (qtype == 2) { int x, y; x = q_array[loopcount][1]; y = q_array[loopcount][2]; printf("%d
", p[x][y]); } else { int x; x = q_array[loopcount][1]; printf("%d
", b[x]); } } if (b) free(b); for (int i = 0; i < s; i++) if (p[i]) free(p[i]); if (p) free(p);}int main() { int input_arr[][3] = {{1, 3, 23}, {1, 4, 128}, {2, 3, 0}, {3, 4, 0}}; solve(4, 4, input_arr);}
输入int input_arr[][3] = {{1, 3, 23}, {1, 4, 128}, {2, 3, 0}, {3, 4, 0}};solve(4, 4, input_arr);
输出231
以上就是c程序示例,演示可变长度数组的用法的详细内容。
其它类似信息

推荐信息