演示变长数组用法的 C 程序
假设我们负责构建一个图书馆系统,监控和查询图书馆的各种操作。我们现在被要求执行三个不同的命令来执行以下操作-
通过使用命令1,我们可以记录在书架x上插入y页的书。
通过使用命令2,我们可以在书架x上打印第y本书的页码。
通过使用命令3,我们可以打印书架x上的书数。
命令以这种格式{commandtype,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.
示例
让我们看看以下实现以获得更好的理解-
#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\n", p[x][y]);
}
else
{
int x;
x = q_array[loopCount][1];
printf("%d\n", 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