LoginSignup
1
1

More than 3 years have passed since last update.

c言語で2次元文字列配列を関数から返すやり方のメモ

Last updated at Posted at 2020-10-04

はじめに

c言語をつかっていて、2次元文字列配列を関数からmain関数に返すやり方のメモを書き残します。
※ポインタ初心者なので、説明が間違っていたらご指摘お願いします。

プログラム


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void test(char**,unsigned int,unsigned int);

const unsigned int sz_fld = 50 + 1;
const unsigned int sz_ffld = 10;

int main(void) {
    char fld[sz_ffld][sz_fld];
    // 配列fldの初期化
    for (unsigned char i=0;i<sz_ffld;++i) {
        strcpy(fld[i],"");
    }

    // mallocで領域確保
    char** pfld = malloc(sz_ffld*sizeof(char*));
    for (unsigned int i=0;i<sz_ffld;++i) {
    // fld配列の先頭のアドレスをplfd(ポインタ型変数)にいれる
        *(pfld+i) = &fld[i][0];
    }

    // ポインタ型変数pfldと2次元配列のそれぞれの要素数sz_ffld,sz_fldを関数に渡す
    test(pfld,sz_ffld,sz_fld);

    // 関数から返ってきた文字列を表示させる部分
    for(int i = 0; i<3; i++){
        printf("%s\n",fld[i]);
    }

    // malloc関数で確保されたメモリを解放
    free(pfld);

    return(0);
}

void test(char** fld,unsigned int m,unsigned int n) {
    // 入力するポインタを用意 
    char a[10][8] = {"1111","2222","3333"};

    for(int i = 0; i<3; i++){
    // a[i]に格納された文字列をstrcpyをつかってポインタが指し示す番地(fld+i)にコピーするイメージ
        strcpy(*(fld+i),a[i]);
    }
    return;
}

結果

paiza.ioで実行してみたら下記のような結果となった。

image.png

参考

1
1
3

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
1
1