ページ 11

c言語で、2次元配列の内の選んだ配列を1つの配列にしたい

Posted: 2022年1月04日(火) 17:18
by アルフリ
例:class[3][5]={{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}}
flag[3]={1,0,1}となるとき、
after[10]={1,2,3,4,5,11,12.13,14,15}を作りたいのですが、うまくいきません。
下のコードだと,after={11,12,13,14,15,0,0,0,0,0}となりました。
これをafter={1,2,3,4,5,11,12.13,14,15}になるようにしたいです。

int main(void){
int i;
int class[3][5]={{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
int flag[3]={1,0,1};
int after[2*5]={0};

for(j=0;j<3;j++){
if(flag[j]==1){
memcpy(after,class[j],sizeof(class[j]));
}
}

printf("after:");
for(i=0;i<3*5;i++){
printf("%d ",after);
}printf("\n");

return 0;
}

Re: c言語で、2次元配列の内の選んだ配列を1つの配列にしたい

Posted: 2022年1月04日(火) 20:28
by あたっしゅ

コード:

/******************************************************************************
https://www.onlinegdb.com/

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, PHP, Ruby, 
C#, VB, Perl, Swift, Prolog, Javascript, Pascal, HTML, CSS, JS
Code, Compile, Run and Debug online from anywhere in world.
*******************************************************************************/
#include <stdio.h>
#include <string.h>

int main(void){
    int i,j,k; // 変更
    int class[3][5]={{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
    int flag[3]={1,0,1};
    int after[2*5]={0};
    int* p=after; // 追加

    for(j=0;j<3;j++){
        if(flag[j]==1){
            //memcpy(after,class[j],sizeof(class[j])); 同じ場所に、重ね書きしている。

            int* q = &class[j][0];  // 追加
            
            for(k=0;k<5;k++) {      // 追加
                *p ++ = *q++;       // 追加
            }                       // 追加
        }
    }

    printf("after:");
    for(i=0;i<2*5;i++){             // 変更 after は [2*5]
        printf("%d ",after[ i ]);
    }
    printf("\n");

    return 0;
}


// end.

Re: c言語で、2次元配列の内の選んだ配列を1つの配列にしたい

Posted: 2022年1月04日(火) 23:08
by アルフリ
変更点なども分かりやすく、どこが間違いだったのかも理解できました。ありがとうございます!