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