C 程序演示可变长数组
假设我们负责构建一个图书馆系统,用于监视和查询图书馆中的各种操作。现在要求我们实现三个不同的命令,执行以下操作 -
使用命令 1,我们可以记录在书架 x 上插入带有 y 页的书。
使用命令 2,我们可以打印书架 x 上第 y 本书的页码。
使用命令 3,我们可以打印书架 x 上的书籍数量。
命令以这种格式 {命令类型,x,y} 作为二维数组提供给我们。如果不存在 y 值,则该值默认为 0。我们打印给定命令的结果。
因此,如果输入类似于书架数 = 4,查询数 = 4,input_arr = {{1, 3, 23}, {1, 4, 128}, {2, 3, 0}, {3, 4, 0}}; 则输出为
23 1
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] := 0
- p[i] := 新数组
- 为初始化循环计数 := 0,当循环计数<q,更新(将循环计数加 1),执行 −
- q 类型 := q_array[loopCount, 0]
- 如果 q 类型和 1 相同,则 −
- x := q_array[loopCount, 1]
- y := q_array[loopCount, 2]
- b[x] := b[x] + 1
- p[x] := 取消分配 p[x] 指向的对象,然后返回大小为
- b[x]
- p[x, b[x] - 1] = y
- 否则,当 q 类型与 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 获取的内存
- 如果 p[i] 不为空,则−
示例
让我们看看以下实现,以便更好地理解 −
#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);输出
23 1
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP