如何将1-D阵列复制到2-D阵列

时间:2015-10-07 08:27:52

标签: c

我有1d数组,我必须像这样复制2D数组

sDaysInMth[0] 31
sDaysInMth[1] 28
sDaysInMth[2] 31
sDaysInMth[3] 30
sDaysInMth[4] 31
sDaysInMth[5] 30
sDaysInMth[6] 31
sDaysInMth[7] 31
sDaysInMth[8] 30
sDaysInMth[9] 31
sDaysInMth[10] 30
sDaysInMth[11] 31

但是这段代码有问题吗?我无法得到正确答案。

    static char pvtsWsMthDayTab[24]="312831303130313130313031";
     char sDaysInMth[12][2] ;
     static char pvtsWsNbrDyMth[3]="";
     int i=0 , j = 0 ;

    memset(pvtsWsNbrDyMth,'\0', sizeof(pvtsWsNbrDyMth));
    memset(sDaysInMth, '\0', sizeof(sDaysInMth));    
     for(i=0; i< 12; i++)
     {
        memcpy(sDaysInMth[i], pvtsWsMthDayTab+(i*2), 2);

     }

    for(i=0;i<12;i++)
    {
        printf("%s ",sDaysInMth[i]); /* printing 2D array*/

        printf("\n");
     }

1 个答案:

答案 0 :(得分:0)

你需要一个char用于最后的\0,我用一个循环来获得2个字符

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



int main(void) { 
    static char pvtsWsMthDayTab[25]="312831303130313130313031"; 
    char sDaysInMth[12][3] ; 

    memset(sDaysInMth, 0, sizeof(sDaysInMth)); 

    for(int i = 0; i < 12; i++) { 
        for (int j = 0; j < 2; j++ ) { 
            sDaysInMth[i][j] = pvtsWsMthDayTab[i * 2 + j ]; 
        } 
    } 

    for(int i = 0; i < 12; i++) { 
        printf("%s\n",sDaysInMth[i]); 
    } 


    return 0; 
}