6
3

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 5 years have passed since last update.

多次元配列を返す関数

Posted at

はじめに

C言語では多次元配列をreturnで返すことできないと勝手に思い込んでいたのですが,どうもできるようなので,備忘録としてここに残しておこうかと.
まあよほどのことがない限りはout引数にするとは思いますが.

方法

以下のコードに示すように,関数の宣言,定義に2次元目以降の要素数を明記してやることで多次元配列を返すことができるようです.

main.cpp

#include <iostream>

// 要素数
constexpr int ARY_SIZE1 = 2;
constexpr int ARY_SIZE2 = 5;

// 多次元配列を持つクラス
class NAryClass
{
private:
	// ARY_SIZE1×ARY_SIZE2の配列
	int mAry[ARY_SIZE1][ARY_SIZE2];

public:
	NAryClass();
	~NAryClass();
	// 2次元配列を返す関数
	int(*getAry())[ARY_SIZE2];
};

// コンストラクタ
NAryClass::NAryClass()
{
	// 適当なデータの設定
	for (int i = 0; i < ARY_SIZE1; i++)
	{
		for (int jj = 0; jj < ARY_SIZE2; jj++)
		{
			mAry[i][jj] = (i + 1) * jj;
		}
	}
}

// デストラクタ
NAryClass::~NAryClass()
{

}

// 多次元配列を返す
int (*NAryClass::getAry())[ARY_SIZE2]
{
	return mAry;
}


int main()
{
	NAryClass nAry;

	// 多次元配列を取得
	int(*nAryData)[ARY_SIZE2] = nAry.getAry();

	// 取得データ表示
	for (int i = 0; i < ARY_SIZE1; i++)
	{
		for (int jj = 0; jj < ARY_SIZE2; jj++)
		{
			std::cout << nAryData[i][jj] << "  ";
		}
		std::cout << std::endl;
	}

    return 0;
}

参考

[C][C++] 2 次元配列を返り値に持つ関数

6
3
2

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
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?