可変長配列の使用法を示すCプログラム
図書館でのさまざまな操作を監視および照会する図書館システムの構築を担当しているとします。ここで、次のことを実行する3つの異なるコマンドを実装するように求められます-
-
コマンド1を使用すると、棚xにyページの本の挿入を記録できます。
-
コマンド2を使用すると、棚xにあるy番目の本のページ番号を印刷できます。
-
コマンド3を使用すると、棚xにある本の数を印刷できます。
コマンドは、この形式{コマンドタイプ、x、y}の2D配列として提供されます。 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
- b [i]:=0
- p [i]:=新しい配列
qtype:=q_array [loopCount、0] qtypeが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
それ以外の場合、qtypeが2と同じ場合、-
- x:=q_array [loopCount、1]
- y:=q_array [loopCount、2]
- print(p [x、y])
それ以外の場合
- x:=q_array [loopCount、1]
- print(b [x])
- bによって取得されたメモリの割り当てを解除します
- p[i]によって取得されたメモリの割り当てを解除します
- 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\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
-
アームストロング数のためのCプログラム
アームストロングかどうかに関係なく、ユーザーが入力した数字nを確認する必要があるタスクが与えられます。 アームストロング数は、すべての桁の合計が桁数で累乗される場合、または桁の順序nと言うことができる場合、桁と同じです。 以下は、アームストロング数を見つける方法の簡単な表現です- 数式- wxyz…. = pow(w, n) +pow(x, n) + pow(y, n) + pow(z, n) + ….. アルゴリズム START Step 1-> Declare a function to find the value after power o
-
C /C++の多次元配列
C / C ++では、多次元配列は簡単な言葉で配列の配列として定義されます。多次元配列では、データは表形式で(行の主要な順序で)格納されます。次の図は、次元が3 x 3x3の多次元配列のメモリ割り当て戦略を示しています。 アルゴリズム Begin Declare dimension of the array. Dynamic allocate 2D array a[][] using new. Fill the array with the elements. Print the ar