0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C言語で要素数を指定せず2次元配列を初期化する

Last updated at Posted at 2022-08-24

C言語で要素数を指定せずに2次元配列を初期化・処理する

C言語で2次元配列を作成し初期値を設定しようとすると行数・列数の両方を指定するか列数を指定する必要があり、その2次元配列は列数まで型の一部という扱いになり素直にポインタで渡す事ができなくなります

double a[][3] = ...;
と宣言した変数を
void function(double* x) {...
で素直に受けることはできない

m行xn列 いくつの行列でもポインタで処理したい時の解決方法です

変数は1次元配列で宣言し行数・列数を引数に取る参照関数を作成する

以下実装です


#include <stdio.h>

double sample1[] = {
    1.0, 2.0, 3.0,
    1.1, 2.1, 3.1,
    1.2, 2.2, 3.2,
    1.3, 2.3, 3.3
};

double sample2[2][3] = {
    {1.0, 2.0, 3.0},
    {1.1, 2.1, 3.1}
};

double vector2_reference(int row_size, int col_size, int row, int col, double* x) {
    return x[row * col_size + col];
}

int main(int argc, char **argv) {
    int i, j;
    for(i = 0; i < 4; i += 1) {
        for(j = 0; j < 3; j += 1) {
            printf("x[%d, %d] = %f\n", i, j, vector2_reference(4, 3, i, j, sample1));
        }
    }
    
    // sample2 を double* で受けようとするとwarningが出る
    //for(i = 0; i < 2; i += 1) {
    //    for(j = 0; j < 3; j += 1) {
    //        printf("x[%d, %d] = %f\n", i, j, vector2_reference(2, 3, i, j, sample2));
    //    }
    //}
    
    return 0;
}

引数5個はスマートでない

vector2_reference関数の引数が5つもあり上長に感じますね、スマートではないですが必要最低限実装でもこうなってしまうので仕方ないですね、n次元配列用の構造体を作ってスマートに見せるのも良い方法だと思います

0
0
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?