LoginSignup
6
5

More than 5 years have passed since last update.

関数内で配列を動的に生成して返す

Last updated at Posted at 2016-03-26

関数内で配列をnewする際、 関数内で操作した配列を呼び出し元に返したいケースにおいて結構迷ってしまったのでメモ。
約数を求める関数を作った場合を例に挙げます。

main.cpp

#include <iostream>
#include <queue>
using namespace std;

//約数の個数を求める
int f(int a, int*& temp){ //配列cのポインタの参照を受け取る

    queue<int> qu;
    int n=0;
    for(int i=1; i<a+1; i++){
        if(a%i==0){
            qu.push(i);
            n++;
        }
    }
    cout << "約数の個数は" << n << endl;

    temp = new int [n]; //配列を動的に確保

    for(int i=0; i<n; i++){
        temp[i]=qu.front();
        qu.pop();
    }

    return n;

}

int main(void){

    int *c;
    int num_div = f(8, c); //num_divに配列の長さ、配列cに約数が格納される

    for(int i=0; i<num_div; i++){
        cout << c[i] << endl; //1,2,4,8が格納されていることがわかる
    {

    delete[] *c;

}

こうすることで約数を確保するのに必要最低限の長さの配列を確保することができます。

6
5
5

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
5